I've used the code posted here: https://stackoverflow.com/a/1551394 in the past on Python2.7 and it's not given me issues before.
I've recently written a Python3 app and I'm seeing times being returned with sometimes one decimal point, and sometimes many decimal points.
from datetime import datetime, timedelta
def pretty_date(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
now = datetime.now()
if type(time) is int:
diff = now - datetime.fromtimestamp(time)
elif isinstance(time,datetime):
diff = now - time
elif not time:
diff = now - now
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return "just now"
if second_diff < 60:
return str(second_diff) + " seconds ago"
if second_diff < 120:
return "a minute ago"
if second_diff < 3600:
return str(second_diff / 60) + " minutes ago"
if second_diff < 7200:
return "an hour ago"
if second_diff < 86400:
return str(second_diff / 3600) + " hours ago"
if day_diff == 1:
return "Yesterday"
if day_diff < 7:
return str(day_diff) + " days ago"
if day_diff < 31:
return str(day_diff / 7) + " weeks ago"
if day_diff < 365:
return str(day_diff / 30) + " months ago"
return str(day_diff / 365) + " years ago"
# Timey Wimey Stuff
now = datetime.now()
nowish = now - timedelta(seconds=10)
hrago = now - timedelta(hours=1)
threehrsago = now - timedelta(hours=3)
sixhrsago = now - timedelta(hours=6)
yesterday = now - timedelta(days=1)
stringTime = "2021-07-11 16:01:57"
timeObject = datetime.strptime(stringTime, '%Y-%m-%d %H:%M:%S')
prettyDate = pretty_date(timeObject)
print (prettyDate)
print (pretty_date(now))
print (pretty_date(nowish))
print (pretty_date(hrago))
print (pretty_date(threehrsago))
print (pretty_date(sixhrsago))
print (pretty_date(yesterday))
See below the contrasting results between 2.7 and 3.8
% python rawTime.py
9 hours ago
just now
10 seconds ago
an hour ago
3 hours ago
6 hours ago
Yesterday
% python3 rawTime.py
9.195277777777777 hours ago
just now
10 seconds ago
an hour ago
3.0 hours ago
6.0 hours ago
Yesterday
Can anyone shed any light on why this might be? I've seen some stuff posted on SO about floating point math and the like (e.g Python3 strange float rounding), however that doesn't really explain why it's fine in 2.7 but not 3.8?