Support future times with timedeltashort tag (#403)

This commit is contained in:
Michael Manfre 2023-01-13 12:54:02 -05:00 committed by GitHub
parent 18b50ce0e6
commit fc8b5be4a0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 3 deletions

View File

@ -14,10 +14,11 @@ def timedeltashort(value: datetime.datetime):
"""
if not value:
return ""
# TODO: Handle things in the future properly
delta = timezone.now() - value
seconds = int(delta.total_seconds())
days = delta.days
sign = "-" if seconds < 0 else ""
seconds = abs(seconds)
days = abs(delta.days)
if seconds < 60:
text = f"{seconds:0n}s"
elif seconds < 60 * 60:
@ -31,7 +32,7 @@ def timedeltashort(value: datetime.datetime):
else:
years = max(days // 365.25, 1)
text = f"{years:0n}y"
return text
return sign + text
@register.simple_tag(takes_context=True)

View File

@ -22,3 +22,11 @@ def test_timedeltashort():
assert timedeltashort(value - timedelta(days=364)) == "364d"
assert timedeltashort(value - timedelta(days=365)) == "1y"
assert timedeltashort(value - timedelta(days=366)) == "1y"
assert timedeltashort(value + timedelta(seconds=2.1)) == "-2s"
assert timedeltashort(value + timedelta(minutes=2, seconds=1)) == "-2m"
assert timedeltashort(value + timedelta(hours=2, seconds=1)) == "-2h"
assert timedeltashort(value + timedelta(days=2)) == "-2d"
assert timedeltashort(value + timedelta(days=364)) == "-364d"
assert timedeltashort(value + timedelta(days=365)) == "-1y"
assert timedeltashort(value + timedelta(days=366)) == "-1y"