in kitsune/sumo/templatetags/jinja_helpers.py [0:0]
def datetimeformat(context, value, format="shortdatetime", use_naturaltime=False):
"""
Returns a formatted date/time using Babel's locale settings. Uses the
timezone from settings.py, if the user has not been authenticated.
"""
if not isinstance(value, datetime.datetime):
# Expecting date value
raise ValueError("Unexpected value {value} passed to datetimeformat".format(value=value))
request = context.get("request")
default_tzinfo = convert_tzinfo = ZoneInfo(settings.TIME_ZONE)
if is_naive(value):
# Since Python 3.9, due to the introduction of the new "fold" parameter, this is the
# recommended way to convert a datetime instance from "naive" to "aware".
new_value = value.replace(tzinfo=default_tzinfo)
else:
new_value = value
if hasattr(request, "session"):
if "timezone" not in request.session:
if hasattr(request, "user") and request.user.is_authenticated:
try:
convert_tzinfo = (
Profile.objects.get(user=request.user).timezone or default_tzinfo
)
except (Profile.DoesNotExist, AttributeError):
pass
request.session["timezone"] = convert_tzinfo
else:
convert_tzinfo = request.session["timezone"] or default_tzinfo
convert_value = new_value.astimezone(convert_tzinfo)
locale = _babel_locale(_contextual_locale(context))
if use_naturaltime and (django_now().astimezone(convert_tzinfo) - convert_value).days < 30:
return naturaltime(convert_value)
if format == "shortdatetime" or format == "shortdate":
# Check if the date is today
today = datetime.datetime.now(tz=convert_tzinfo).toordinal()
kwargs = {"format": "short", "tzinfo": convert_tzinfo, "locale": locale}
if convert_value.toordinal() == today:
formatted = _lazy("Today at %s") % format_time(convert_value, **kwargs)
else:
if format == "shortdatetime":
formatted = format_datetime(convert_value, **kwargs)
else:
del kwargs["tzinfo"]
formatted = format_date(convert_value, **kwargs)
elif format == "longdatetime":
formatted = format_datetime(
convert_value, format="long", tzinfo=convert_tzinfo, locale=locale
)
elif format == "date":
formatted = format_date(convert_value, locale=locale)
elif format == "time":
formatted = format_time(convert_value, tzinfo=convert_tzinfo, locale=locale)
elif format == "datetime":
formatted = format_datetime(convert_value, tzinfo=convert_tzinfo, locale=locale)
elif format == "year":
formatted = format_datetime(
convert_value, format="yyyy", tzinfo=convert_tzinfo, locale=locale
)
else:
# Unknown format
raise DateTimeFormatError
return Markup('<time datetime="%s">%s</time>' % (convert_value.isoformat(), formatted))