时区时间戳奇怪

Timezone Timestamp Weirdness

我发现 Python 中不同时区的行为非常奇怪。以下代码:

import datetime as dtm
import pytz


def test_tz():
    america_ny_tz: dtm.tzinfo = pytz.timezone("America/New_York")
    est_tz: dtm.tzinfo = pytz.timezone("EST5EDT")

    today = dtm.date.today()

    ny_dtm = dtm.datetime(
        year=today.year, month=today.month, day=today.day, tzinfo=america_ny_tz
    )
    est_dtm = dtm.datetime(
        year=today.year, month=today.month, day=today.day, tzinfo=est_tz
    )

    print(f"New York: {ny_dtm.timestamp()}, EST: {est_dtm.timestamp()}")


if __name__ == "__main__":
    test_tz()

输出:

New York: 1609995360.0, EST: 1609995600.0

正如您可能注意到的那样,差异大约是 4 分钟,因此人们必须假设时间应该相同。

我是否错误地访问了时区信息,或者我认为时区信息应该相同?

运行 在 Linux、Ubuntu 20.04 上,但在 18.04 上的行为是相同的。

P.S。我没有尝试其他语言或不同的操作系统来查看行为是否相同。

这似乎是因为一个时区使用本地标准时间而另一个时区是 UTC(世界协调时间)的偏移量。

>>> pytz.timezone("America/New_York")
<DstTzInfo 'America/New_York' LMT-1 day, 19:04:00 STD>
>>> pytz.timezone("EST5EDT")
<DstTzInfo 'EST5EDT' EST-1 day, 19:00:00 STD>
>>> pytz.timezone("LMT")

来自https://www.timeanddate.com/time/local-mean-time.html

Local Mean Time was officially used as civil time in many countries during the 19th century. Each city had a different local time defined by its longitude, the difference amounting to 4 minutes per degree longtitude. This equals a distance of 50 miles or 81 kilometers on New York's latitude.

您需要正确本地化 - 使用 pytz 的时区对象,在创建日期时间对象时直接设置 tzinfo 不是 正确的方法。这是 in the docs:

This library only supports two ways of building a localized time. The first is to use the localize() method provided by the pytz library.

The second way of building a localized time is by converting an existing localized time using the standard astimezone() method


另一方面,如果您碰巧使用 Python 3.9+,您可以使用标准库中的 zoneinfo 模块让您的生活更轻松 - 请参阅 the docs / using-zoneinfo or example usage here