问题
I am trying to convert an aware datetime (UTC) to a local time using pytz.
I was using this snippet of code, which lead to the time being off by a few minutes
new_timezone = pytz.timezone(local_timezone)
new_datetime = entry[1].replace(tzinfo=timezone.utc).astimezone(tz=new_timezone)
I tried to do this, but get an error that it is not a naive datetime:
local_timezone_pytz.localize(entry[1])
回答1:
use astimezone
, e.g.:
import datetime
import pytz
dt = datetime.datetime.now(datetime.timezone.utc)
# datetime.datetime(2020, 10, 22, 5, 48, 5, 806183, tzinfo=datetime.timezone.utc)
dt_est = dt.astimezone(pytz.timezone('US/Eastern'))
# datetime.datetime(2020, 10, 22, 1, 48, 5, 806183, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
Note that this is not specific to pytz
; you can also supply a timezone object from dateutil.tz.gettz
or zoneinfo.ZoneInfo
to astimezone
.
来源:https://stackoverflow.com/questions/64472668/pytz-localise-on-aware-datetime