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?
UtcNow tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer. DateTime. Now gives the date and time as it would appear to someone in your current locale.
Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
The pytz package encourages using UTC for internal timezone representation by including a special UTC implementation based on the standard Python reference implementation in the Python documentation. The UTC timezone unpickles to be the same instance, and pickles to a smaller size than other pytz tzinfo instances.
datetime. now() is in UTC and not local time zone in 0.118 #43412.
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.
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