Answer a question

I am using the datetime.datetime class from the Python standard library. I wish to construct an instance of this class with the UTC timezone. To do so, I gather that I need to pass as the tzinfo argument to the datetime constructor some instance of the tzinfo class.

The documentation for the tzinfo class says that:

tzinfo is an abstract base class, meaning that this class should not be instantiated directly. You need to derive a concrete subclass, and (at least) supply implementations of the standard tzinfo methods needed by the datetime methods you use. The datetime module does not supply any concrete subclasses of tzinfo.

Now I'm stumped. All I want to do is represent "UTC". I should be able to do that using approximately three characters, like this

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 to do. So what's my alternative?

Answers

There are fixed-offset timezones in the stdlib since Python 3.2:

from datetime import datetime, timezone

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

Constructor is :

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

Docs link.

Though it is easy to implement utc timezone on earlier versions:

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)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐