Pytz Localise on Aware Datetime

北城以北 提交于 2020-12-15 06:18:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!