Improvement
If else
def timesince(date):
now = timezone.now()
diff = now - date
if diff.days == 0 and diff.seconds >= 0 and diff.seconds < 60:
return ' just now'
if diff.days == 0 and diff.seconds >= 60 and diff.seconds < 3600:
return str(math.floor(diff.seconds / 60)) + " minutes ago"
if diff.days == 0 and diff.seconds >= 3600 and diff.seconds < 86400:
return str(math.floor(diff.seconds / 3600)) + " hours ago"
if diff.days == 1 and diff.days < 30:
return str(diff.days) + " day ago"
if diff.days >= 1 and diff.days < 30:
return str(diff.days) + " days ago"
if diff.days >= 30 and diff.days < 365:
return str(math.floor(diff.days / 30)) + " months ago"
if diff.days >= 365:
return str(math.floor(diff.days / 365)) + " years ago"
import bisect
# BREAKPOINTS 必须是已经排好序的,不然无法进行二分查找
BREAKPOINTS = (1, 60, 3600, 3600 * 24)
TMPLS = (
# unit, template
(1, "less than 1 second ago"),
(1, "{units} seconds ago"),
(60, "{units} minutes ago"),
(3600, "{units} hours ago"),
(3600 * 24, "{units} days ago"),
)
def from_now(ts):
"""接收一个过去的时间戳,返回距离当前时间的相对时间文字描述
"""
seconds_delta = int(time.time() - ts)
unit, tmpl = TMPLS[bisect.bisect(BREAKPOINTS, seconds_delta)]
return tmpl.format(units=seconds_delta // unit)
import time
import datetime
now = time.time()
print(from_now(now))
print(from_now(now - 24))
print(from_now(now - 600))
print(from_now(now - 7500))
print(from_now(now - 87500))
less than 1 second ago
24 seconds ago
10 minutes ago
2 hours ago
1 days agoUsing Iterable in parameter
Last updated
Was this helpful?