Issue
I have a a basic string + another string which reresents timezone. I’m trying to return the UTC equivalent..
timezone = "America/New_York"
scheduleDate = "2021-09-21 21:00:00"
dtimestamp = datetime.datetime.strptime(scheduleDate, '%Y-%m-%d %H:%M:%S').astimezone(
pytz.timezone(timezone)).timestamp()
sdate = datetime.datetime.utcfromtimestamp(dtimestamp).strftime('%Y-%m-%dT%H:%M:%SZ')
print(sdate)
Solution
This works, but not sure if there’s a better approach for this. I haven’t looked too closely at the pytz
docs before.
from datetime import datetime
import pytz
timezone = "America/New_York"
scheduleDate = "2021-09-21 21:00:00"
# Convert to naive datetime
dt_naive: datetime = datetime.strptime(scheduleDate, '%Y-%m-%d %H:%M:%S')
# localize datetime with ET timezone
dt: datetime = pytz.timezone(timezone).localize(dt_naive)
# normalize datetime to UTC time
dt_utc: datetime = pytz.utc.normalize(dt)
print(str(dt_utc))
Answered By – rv.kvetch
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0