Python - simplest and most coherent way to get tim

2020-02-06 04:50发布

datetime.now() doesn't appear to have timezone info attached. I want the current time in UTC. What do 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() was the obvious solution, but then I discovered that it doesn't have timezone info attached either (WTF?).

>>> from datetime import datetime
>>> y = datetime.utcnow()
>>> y
datetime.datetime(2014, 3, 11, 16, 19, 40, 238810)

3条回答
乱世女痞
2楼-- · 2020-02-06 05:09

In Python 3:

datetime.now(timezone.utc)

In Python 2.x there is no timezone object, 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.

查看更多
Root(大扎)
3楼-- · 2020-02-06 05:15

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

Adapting from this answer, here is how to make the object timezone-aware.

>>> import pytz
>>> from datetime import datetime
>>> datetime.now(pytz.utc)
datetime.datetime(2014, 3, 11, 15, 34, 52, 229959, tzinfo=<UTC>)
查看更多
唯我独甜
4楼-- · 2020-02-06 05:16

I use pytz

Then use the following bit of code

import pytz
from datetime import datetime
now = datetime.utcnow().replace(tzinfo = pytz.utc)
查看更多
登录 后发表回答