freezegun icon indicating copy to clipboard operation
freezegun copied to clipboard

time.localtime still uses original timezone information

Open lbckmnn opened this issue 3 years ago • 5 comments

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

lbckmnn avatar Feb 21 '23 10:02 lbckmnn

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.

boxed avatar Feb 21 '23 14:02 boxed

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.

lbckmnn avatar Feb 21 '23 14:02 lbckmnn

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

boxed avatar Feb 21 '23 15:02 boxed

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

lbckmnn avatar Feb 21 '23 15:02 lbckmnn

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

edgarrmondragon avatar Jun 21 '24 09:06 edgarrmondragon