I cannot understand how to use information on the current datetime in the code at the bottom. I calculated the current datetime as
import datetime
now = datetime.now()
reftime1 = datetime(now.year,now.month,now.day,now.hour) # only NaN values
vs the example in the code below
reftime2 = datetime.datetime(2021,4,10,20) # no error
The code (From string to datetime, looking at the current (local) time) where I would like to replace reftime1
is
import datetime
import dateparser
def timedelta2str(sec):
hours, remainder = divmod(sec, 3600)
return f'{int(hours):02}:{int(remainder//60):02}'
def formatTimeAgo(string, reftime):
dtobj = dateparser.parse(string, settings={'RELATIVE_BASE': reftime})
if isinstance(dtobj, datetime.datetime):
td = reftime - dtobj
if td >= datetime.timedelta(1):
return timedelta2str(td.total_seconds())
else:
return (reftime-td).strftime('%H:%M')
else:
return "N/A"
# exemplary input
t = ("10 hours", "6 hours", "2 days", "1 day")
reftime1 = datetime.datetime(2021,4,10,20) # here
for elem in t:
print(elem, '->', formatTimeAgo(elem, reftime1))
I would need an explanation on what is wrong in my replacement.