When to use datetime.utcnow() or datetime.now(tz=pytz.utc).replace(tzinfo=None)

Aert picture Aert · Feb 24, 2017 · Viewed 8.3k times · Source

I would like to understand when I should be using

datetime.now(tz=pytz.utc).replace(tzinfo=None)

as opposed to simply

datetime.utcnow()

Will the latter not take into account e.g. daylight savings?

Answer

Meghdeep Ray picture Meghdeep Ray · Feb 24, 2017

A lot of how datetime.datetime will work depends on the machine it is run on. The local time and time zone settings of the host machine will determine the output you will get.

If the host machine is in the UTC timezone then there will be no difference between datetime.datetime.now() and datetime.datetime.utcnow().

According to the pytz documentation:

The preferred way of dealing with times is to always work in UTC, converting to localtime only when generating output to be read by humans.

pytz is used for accounting for daylight savings time, and datetime.datetime.utcnow() is used to provide a universal standardised reference point upon which you can calculate daylight savings. datetime.datetime.utcnow() on it's own will not account for daylight savings.