I'm puzzled why a function that freezes time with freezegun outputs different UTC times depending on whether datetime.datetime.utcnow()
is called, or datetime.datetime.now(pytz.utc)
. I'm not saying it's broken, just that I don't understand why, and would like to know!
eg, using this function:
@freeze_time("2012-01-14 03:21:34", tz_offset=-4)
def test():
print("utcnow(): %s" % datetime.datetime.utcnow())
print("pytz.utc: %s" % datetime.datetime.now(pytz.utc))
the output is:
utcnow(): 2012-01-14 03:21:34
pytz.utc: 2012-01-13 23:21:34+00:00
I guess the first is a naive datetime, but why are they different times?
(Ultimately why I want to know: if I'm using freezegun in my tests, and I use pytz to generate times in my code being tested, I want to know what its 'correct' behaviour should be.)
The property Now of the DateTime class returns the current date and time of the machine running the code, expressed in the computer's local time. The property UtcNow of the DateTime class returns the current date and time of the machine running the code, expressed in UTC format.
Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
Intro to Timezone Aware and Not Timezone Aware We'll need two Python libraries for this, pytz and Python's datetime . In the example above, we know utcnow is UTC, but it is not timezone-aware.
This is an issue within freezegun see here and here.
It does not look like that this will be fixed soon. In the end I used this as a workaround:
def freezegun_utc_workaround():
return datetime.utcnow().replace(tzinfo=pytz.utc)
For this
datetime.datetime.now(pytz.utc)
May be it is even better to wrap this and patch it manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With