Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using freezegun, why do pytz.utc and utcnow() output different datetimes?

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

like image 423
Phil Gyford Avatar asked Jul 02 '15 20:07

Phil Gyford


People also ask

What is the difference between DateTime now and DateTime Utcnow?

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.

What is Utcnow ()?

Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).

Is DateTime Utcnow timezone aware?

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.


1 Answers

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.

like image 129
crasu Avatar answered Oct 08 '22 13:10

crasu