Python datetime.now() with timezone

99封情书 提交于 2020-01-17 11:12:05

问题


I have a timezone which is float (for example 4.0).
I want to construct datetime with given timezone.

I tried this,

datetime.now(timezone)

but it throws

TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'float'

So I wonder how can I make tzinfo from float?


回答1:


If you are using Python 3.2 or newer, you need to create a datetime.timezone() object; it takes an offset as a datetime.timedelta():

offset = timezone(timedelta(hours=timezone)
datetime.now(offset))

For earlier Python versions, it'll be easiest to use an external library to define a timezone object for you.

The dateutil library includes objects to take a numerical offset to create a timezone object:

from dateutil.tz import tzoffset

offset = tzoffset(None, timezone * 3600)  # offset in seconds
datetime.now(offset)



回答2:


I suggest you to use pytz, it could be more simple According to the description:

This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference

LINK



来源:https://stackoverflow.com/questions/30712064/python-datetime-now-with-timezone

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