refactor: pretty_date

This commit is contained in:
barredterra 2023-04-11 15:44:03 +02:00
parent d7b474f4ac
commit 9f1feaab02

View file

@ -1518,51 +1518,16 @@ def pretty_date(iso_datetime: datetime.datetime | str) -> str:
long ago the date represents.
Ported from PrettyDate by John Resig
"""
from frappe import _
if not iso_datetime:
return ""
import math
from babel.dates import format_timedelta
if isinstance(iso_datetime, str):
iso_datetime = datetime.datetime.strptime(iso_datetime, DATETIME_FORMAT)
now_dt = datetime.datetime.strptime(now(), DATETIME_FORMAT)
dt_diff = now_dt - iso_datetime
# available only in python 2.7+
# dt_diff_seconds = dt_diff.total_seconds()
dt_diff_seconds = dt_diff.days * 86400.0 + dt_diff.seconds
dt_diff_days = math.floor(dt_diff_seconds / 86400.0)
# differnt cases
if dt_diff_seconds < 60.0:
return _("just now")
elif dt_diff_seconds < 120.0:
return _("1 minute ago")
elif dt_diff_seconds < 3600.0:
return _("{0} minutes ago").format(cint(math.floor(dt_diff_seconds / 60.0)))
elif dt_diff_seconds < 7200.0:
return _("1 hour ago")
elif dt_diff_seconds < 86400.0:
return _("{0} hours ago").format(cint(math.floor(dt_diff_seconds / 3600.0)))
elif dt_diff_days == 1.0:
return _("Yesterday")
elif dt_diff_days < 7.0:
return _("{0} days ago").format(cint(dt_diff_days))
elif dt_diff_days < 14:
return _("1 week ago")
elif dt_diff_days < 31.0:
return _("{0} weeks ago").format(dt_diff_days // 7)
elif dt_diff_days < 61.0:
return _("1 month ago")
elif dt_diff_days < 365.0:
return _("{0} months ago").format(dt_diff_days // 30)
elif dt_diff_days < 730.0:
return _("1 year ago")
else:
return _("{0} years ago").format(dt_diff_days // 365)
locale = frappe.local.lang.replace("-", "_") if frappe.local.lang else None
return format_timedelta(iso_datetime - now_dt, add_direction=True, locale=locale)
def comma_or(some_list, add_quotes=True):