Change Timezone for Date object Python

 ̄綄美尐妖づ 提交于 2019-12-05 10:28:41

The most robust way to do this is to use pytz. You can install it simply with pip install pytz.

To get the local date with pytz, you can simply do this (note that the date.today method will not take a timezone):

>>> from datetime import datetime
>>> import pytz
>>> local_date = datetime.now(pytz.timezone('US/Central'))  # use datetime here
>>> local_date.date()                                       # now call date method
datetime.date(2014, 11, 30)

Compare that to the present Greenwich date:

>>> greenwich_date = datetime.now(pytz.timezone('Etc/Greenwich'))
>>> greenwich_date.date()
datetime.date(2014, 12, 1)

In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class. The pytz library has an up-to-date database of most timezones. You can therefore do:

import pytz
from datetime import datetime
datetime.now(pytz.utc)

The .utc gives you a localized timezone by default, but you may wish to explicitly provide another timezone using .timezone() method.

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