How to convert a datetime from one arbitrary timezone to another arbitrary timezone

强颜欢笑 提交于 2019-12-05 21:44:27

To convert a timezone-aware datetime object into a different timezone, use datetime.astimezone() method:

pacific_time = ests1.astimezone(pytz.timezone('US/Pacific'))

In general, pytz docs recommend to call pytz.timezone('US/Pacific').normalize() on the result but you don't need it here because ests1 timezone has a fixed utc offset.

I think I got it right this time:

from datetime import datetime as dtime
import pytz
from colander import iso8601

ests1 = iso8601.parse_date('2016-04-01T00:00:00.0000-04:00')
epoch = dtime(1970, 1, 1, tzinfo=pytz.UTC)          # 1970-01-01T00:00:00+00:00
ept = (ests1 - epoch).total_seconds()               # 1459483200.0

utc_date = dtime.fromtimestamp(ept, tz=pytz.UTC)    # 2016-04-01T04:00:00+00:00
ptz = pytz.timezone('US/Pacific')
pst_date = dtime.fromtimestamp(ept, tz=ptz)         # 2016-03-31T21:00:00-07:00

ests2 = iso8601.parse_date('2016-02-01T00:00:00.0000-04:00')
ept2 = (ests2 - epoch).total_seconds()              # 1454299200.00

utc_date2 = dtime.fromtimestamp(ept2, tz=pytz.UTC)  # 2016-02-01T04:00:00+00:00
pst_date2 = dtime.fromtimestamp(ept2, tz=ptz)       # 2016-01-31T20:00:00-08:00

so, it seems to be as simple as

def convert_to_tz(dt,tz_new):
   seconds = (dt - epoch).total_seconds()
   return dtime.fromtimestamp(seconds, tz=tz_new)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!