Python datetime.now() 带时区

Python datetime.now() with timezone

我有一个浮动时区(例如 4.0)。
我想用给定的时区构造 datetime

我试过了,

datetime.now(timezone)

但它抛出

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

所以我想知道如何从 float 中生成 tzinfo

我建议你使用pytz,因为它可能更简单。

根据描述:

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

>>> from datetime import datetime
>>> import pytz

>>> datetime.now(tz=pytz.UTC)
datetime.datetime(2021, 11, 12, 20, 59, 54, 579812, tzinfo=<UTC>)

>>> datetime.now(tz=pytz.timezone("Europe/Oslo"))
datetime.datetime(2021, 11, 12, 22, 0, 4, 911480, tzinfo=<DstTzInfo 'Europe/Oslo' CET+1:00:00 STD>)

>>> [tz for tz in pytz.common_timezones if tz.startswith("US")]
['US/Alaska',
 'US/Arizona',
 'US/Central',
 'US/Eastern',
 'US/Hawaii',
 'US/Mountain',
 'US/Pacific']
 

如果您使用的是 Python 3.2 或更新版本,您需要创建一个 datetime.timezone() object; it takes an offset as a datetime.timedelta():

from datetime import datetime, timezone, timedelta

timezone_offset = -8.0  # Pacific Standard Time (UTC−08:00)
tzinfo = timezone(timedelta(hours=timezone_offset))
datetime.now(tzinfo)

对于早期的 Python 版本,使用外部库为您定义时区对象是最简单的。

dateutil library 包括采用数值偏移来创建时区对象的对象:

from dateutil.tz import tzoffset

timezone_offset = -8.0  # Pacific Standard Time (UTC−08:00)
tzinfo = tzoffset(None, timezone_offset * 3600)  # offset in seconds
datetime.now(tzinfo)

Python 3.9带来了IANA tz database support (pytz-like) as zoneinfo.

由于夏令时,建议使用 IANA 名称而不是静态 UTC 偏移量。