带有时区的Python datetime.now() [英] Python datetime.now() with timezone
问题描述
我有一个浮动的时区(例如4.0)。
我想用给定的时区构造 datetime
。
I have a timezone which is float (for example 4.0).
I want to construct datetime
with given timezone.
我尝试过这个,
datetime.now(timezone)
但它会抛出
TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'float'
如何从float生成 tzinfo
?
So I wonder how can I make tzinfo
from float?
推荐答案
如果使用的是Python 3.2或更高版本,您需要创建一个 datetime .timezone()
对象;它需要一个偏移量作为 datetime.timedelta()
:
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))
对于早期的Python版本,使用外部变量最简单库来为您定义时区对象。
For earlier Python versions, it'll be easiest to use an external library to define a timezone object for you.
dateutil
库包括一些对象,这些对象采用数字偏移量来创建时区对象:
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)
这篇关于带有时区的Python datetime.now()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!