Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 256
Aert Avatar asked Feb 24 '17 07:02

Aert


People also ask

What is the difference between datetime now and datetime UtcNow?

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.

Does datetime use UTC?

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

What is pytz 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.

What timezone is datetime NOW ()?

datetime. now() is in UTC and not local time zone in 0.118 #43412.


1 Answers

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.

like image 157
Meghdeep Ray Avatar answered Oct 03 '22 09:10

Meghdeep Ray