Is the simplest and most consistent way to get the current time, corresponding to the time in UTC?

datetime.now() does not seem to provide timezone information. I want the current time in UTC. What should I do?

 >>> from datetime import datetime >>> y = datetime.now() >>> y datetime.datetime(2014, 3, 11, 11, 18, 33, 598489) 

At first I thought datetime.utcnow() an obvious solution, but then I found that it does not have time zone information (WTF?).

 >>> from datetime import datetime >>> y = datetime.utcnow() >>> y datetime.datetime(2014, 3, 11, 16, 19, 40, 238810) 
+2
source share
3 answers

I am using pytz

Then use the following bit of code

 import pytz from datetime import datetime now = datetime.utcnow().replace(tzinfo = pytz.utc) 
+1
source

In Python 3:

 datetime.now(timezone.utc) 

There is no timezone object in Python 2.x, but you can write your own:

 try: from datetime import timezone except ImportError: from datetime import tzinfo, timedelta class timezone(tzinfo): def __init__(self, utcoffset, name=None): self._utcoffset = utcoffset self._name = name def utcoffset(self, dt): return self._utcoffset def tzname(self, dt): return self._name def dst(self, dt): return timedelta(0) timezone.utc = timezone(timedelta(0), 'UTC') 

Then you can do datetime.now(timezone.utc) just like in Python 3.

+3
source

Use datetime.utcnow() for the current time in UTC.

Adapting from this answer, here's how to make an object a time zone.

 >>> import pytz >>> from datetime import datetime >>> datetime.now(pytz.utc) datetime.datetime(2014, 3, 11, 15, 34, 52, 229959, tzinfo=<UTC>) 
+1
source

Source: https://habr.com/ru/post/982392/


All Articles