How to convert UTC to EST with Python and take care of daylight saving automatically?

时间秒杀一切 提交于 2019-12-05 21:30:42

You'll need to use the pytz module (available from PyPI):

import pytz
from datetime import datetime

est = pytz.timezone('US/Eastern')
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S %Z%z'

winter = datetime(2016, 1, 24, 18, 0, 0, tzinfo=utc)
summer = datetime(2016, 7, 24, 18, 0, 0, tzinfo=utc)

print winter.strftime(fmt)
print summer.strftime(fmt)

print winter.astimezone(est).strftime(fmt)
print summer.astimezone(est).strftime(fmt)

which will print:

2016-01-24 18:00:00 UTC+0000
2016-07-24 18:00:00 UTC+0000
2016-01-24 13:00:00 EST-0500
2016-07-24 14:00:00 EDT-0400

The reason why you'll need to use 'US/Eastern' and not 'EST' is exemplified in the last two lines of output.

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