Search code examples
pythondatetimetimezonepytz

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


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?


Solution

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