Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does datetime.datetime.utcnow() not contain timezone information?

datetime.datetime.utcnow() 

Why does this datetime not have any timezone info given that it is explicitly a UTC datetime?

I would expect that this would contain tzinfo.

like image 867
Vitaly Babiy Avatar asked Feb 25 '10 04:02

Vitaly Babiy


People also ask

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

What timezone is datetime now Python?

As specified in python docs, . now(pytz_timezone) does exactly the same as localize(utcnow) - first it generates current time in UTC, then it assigns it a timezone: "<...>

Does datetime return UTC?

Since our system is running on Ubuntu 20.04 Linux server, from our tests, we found that all DateTime. Now call will return a UTC time, not local time.

Is datetime always in UTC?

As soon as you handle dates or times, handle them in UTC. Why UTC? Because it's Coordinated Universal Time. Universal means it's a standard understood anywhere.


2 Answers

Note that for Python 3.2 onwards, the datetime module contains datetime.timezone. The documentation for datetime.utcnow() says:

An aware current UTC datetime can be obtained by calling datetime.now(timezone.utc).

So, datetime.utcnow() doesn't set tzinfo to indicate that it is UTC, but datetime.now(datetime.timezone.utc) does return UTC time with tzinfo set.

So you can do:

>>> import datetime >>> datetime.datetime.now(datetime.timezone.utc) datetime.datetime(2014, 7, 10, 2, 43, 55, 230107, tzinfo=datetime.timezone.utc) 
like image 186
Craig McQueen Avatar answered Oct 19 '22 08:10

Craig McQueen


That means it is timezone naive, so you can't use it with datetime.astimezone

you can give it a timezone like this

import pytz  # 3rd party: $ pip install pytz  u = datetime.utcnow() u = u.replace(tzinfo=pytz.utc) #NOTE: it works only with a fixed utc offset 

now you can change timezones

print(u.astimezone(pytz.timezone("America/New_York"))) 

To get the current time in a given timezone, you could pass tzinfo to datetime.now() directly:

#!/usr/bin/env python from datetime import datetime import pytz # $ pip install pytz  print(datetime.now(pytz.timezone("America/New_York"))) 

It works for any timezone including those that observe daylight saving time (DST) i.e., it works for timezones that may have different utc offsets at different times (non-fixed utc offset). Don't use tz.localize(datetime.now()) -- it may fail during end-of-DST transition when the local time is ambiguous.

like image 42
John La Rooy Avatar answered Oct 19 '22 09:10

John La Rooy