from datetime import datetime
import pytz
cur_time = datetime.now()
cur_time = pytz.utc.localize(cur_time)
rr_name = 'xx_20211005141746.txt'
rr_time = re.search('_(.*).txt', rr_name).group(1)
rr_time = datetime.strptime(rr_time, '%Y%m%d%H%M%S')
tzone = "Europe/London"
hb_time = pytz.utc.localize(rr_time).astimezone(pytz.timezone(tzone))
diff = cur_time - hb_time
l_heared = round((diff.total_seconds() / 60), 2)
The difference between cur_time
and rr_time
is around 6 minutes, which is 360 seconds. How comes delta gives me back 77.65
seconds...
Please note cur_time
and rr_name
are native datetimes
CodePudding user response:
Use the total_seconds
method:
print(f'{delta.total_seconds()} seconds')
output: 337.525332 seconds
CodePudding user response:
You'll have to set the correct time zone for date/time stored in the filename directly, don't set it to UTC first and then convert:
import re
from datetime import datetime
from zoneinfo import ZoneInfo # Python 3.9 ; there is backports.zoneinfo for older versions
# import pytz
now = datetime.now(ZoneInfo('UTC'))
# now = datetime.now(pytz.UTC)
print(now.astimezone(ZoneInfo('Europe/London')))
# 2021-10-05 14:58:43.957950 01:00
rr_name = 'xx_20211005141746.txt' # time zone Europe/London in filename ...
rr_time = re.search('_(.*).txt', rr_name).group(1)
rr_time = datetime.strptime(rr_time, '%Y%m%d%H%M%S').replace(tzinfo=ZoneInfo('Europe/London'))
# rr_time = pytz.timezone('Europe/London').localize(datetime.strptime(rr_time, '%Y%m%d%H%M%S'))
print(rr_time)
# 2021-10-05 14:17:46 01:00
l_heared = round(((now-rr_time).total_seconds() / 60), 2)
print(l_heared, "minutes ago")
# 40.97 minutes ago