Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

linux - Python Timezone Timestamp Wierdness

I am finding a very strange behavior for different timezones in Python. The following code:

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()

outputs:

New York: 1609995360.0, EST: 1609995600.0

As you may notice the difference is about 4 minutes where one would have to assume the time should be the same.

Am I accessing Time Zone information incorrectly or is my understanding that the Time Zone information should be the same?

Running on Linux, Ubuntu 20.04 but the behavior on 18.04 was the same.

P.S. I haven't tried other languages or different OS' to see if the behavior will be the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to localize correctly - with pytz's timezone objects, setting tzinfo directly when creating the datetime object is not the right way. It's 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.

and

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


On the other hand, if you happen to use Python 3.9+, you can use the zoneinfo module from the standard lib to make you life easier - see the docs / using-zoneinfo or example usage here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...