spulec / freezegun

Let your Python tests travel through time
Apache License 2.0
4.19k stars 269 forks source link

time.localtime still uses original timezone information #494

Open lbckmnn opened 1 year ago

lbckmnn commented 1 year ago

When the time is frozen, datetime.datetime.now() and datetime.datetime.utcnow() return the same value, indicating that the timezone in this scenario is utc. However, time.localtime() does not return the same value as datetime.datetime.now() anymore. time.localtime() still takes into account the actual timezone of the system.

Minimal example:

import datetime
import time

import freezegun

if __name__ == "__main__":
    target_time = datetime.datetime.now()
    print(target_time)
    print(time.localtime())
    print(datetime.datetime.utcnow())

    with freezegun.freeze_time(target_time):
        print(datetime.datetime.now())
        print(time.localtime(time.time()))
        print(datetime.datetime.utcnow())

Output:

2023-02-21 14:54:39.964024
time.struct_time(tm_year=2023, tm_mon=2, tm_mday=21, tm_hour=14, tm_min=54, tm_sec=39, tm_wday=1, tm_yday=52, tm_isdst=0)
2023-02-21 13:54:39.964071
2023-02-21 14:54:39.964024
time.struct_time(tm_year=2023, tm_mon=2, tm_mday=21, tm_hour=15, tm_min=54, tm_sec=39, tm_wday=1, tm_yday=52, tm_isdst=0)
2023-02-21 14:54:39.964024
boxed commented 1 year ago

https://github.com/spulec/freezegun/issues/348 https://github.com/spulec/freezegun/issues/204 https://github.com/spulec/freezegun/issues/89

All seem like basically the same thing?

89 specifically has a long discussion where we try to figure out what it SHOULD be doing. I would welcome someone tackling this and I will argue to spulec that any such person be given commit/merge access.

I personally don't use freezegun anymore and have switched totally to time-machine, so I won't be spending more time with this.

lbckmnn commented 1 year ago

Yes #204 is indeed the exact same issue.

Well, for my usecase i don't really care whether the passed time is utc or something else. The problem is, that datetime.datetime.now() returns the utc time once frozen and time.localtime() doesn't. That is really inconsistent. For my usecase, I need datetime.datetime.now() and time.localtime()to return the same time.

boxed commented 1 year ago

If you're not using pypy, I strongly recommend you switch to time-machine. It's quite easy to switch in my experience.

lbckmnn commented 1 year ago

Yes, thats what i have done now. Thanks for the suggestion!

edgarrmondragon commented 4 months ago

For folks migrating to time-machine because of this, you might wanna be aware of https://github.com/adamchainz/time-machine/issues/325#issuecomment-1427013470