How to create a UTC `datetime` object in Python?

I am using the datetime.datetime class from the Python standard library. I want to build an instance of this class with a UTC timezone. To do this, I understand that I need to pass a datetime constructor as an argument to tzinfo instance of the tzinfo class .

The documentation for the tzinfo class says that:

tzinfo is an abstract base class, which means that this class should not be created directly. You need to get a specific subclass and (at least) implementation of the delivery of standard tzinfo methods needed to use the datetime methods that you use. The datetime module datetime not provide any specific tzinfo subclasses.

Now I'm at a standstill. All I want to do is UTC. I have to do this using approximately three characters, for example

 import timezones ... t = datetime(2015, 2, 1, 15, 16, 17, 345, timezones.UTC) 

In short, I'm not going to do what the documentation tells me. So what is my alternative?

+7
python timezone datetime
source share
2 answers

There are fixed time intervals in stdlib since Python 3.2:

 from datetime import datetime, timezone t = datetime(2015, 2, 1, 15, 16, 17, 345, tzinfo=timezone.utc) 

Although in earlier versions, the utc timezone is simple:

 from datetime import tzinfo, timedelta, datetime ZERO = timedelta(0) class UTCtzinfo(tzinfo): def utcoffset(self, dt): return ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return ZERO utc = UTCtzinfo() t = datetime(2015, 2, 1, 15, 16, 17, 345, tzinfo=utc) 
+12
source share

I have used a lot in pytz and am very pleased with this module.

pytz

pytz displays the Olson tz in Python. This library allows accurate and cross-platform timezone calculations using Python 2.4 or higher. It also solves the ambiguous time problem at the end of daylight saving time, which you can learn more about in the Python Library Reference ( datetime.tzinfo ).

I would also recommend reading: Understanding the DateTime, tzinfo, timedelta, and TimeZone events in python

+3
source share

All Articles