2

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)
tadasajon
  • 14,276
  • 29
  • 92
  • 144

3 Answers3

4

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.

lyschoening
  • 18,170
  • 11
  • 44
  • 54
1

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>)
Community
  • 1
  • 1
vivekagr
  • 1,786
  • 15
  • 23
1

I use pytz

Then use the following bit of code

import pytz
from datetime import datetime
now = datetime.utcnow().replace(tzinfo = pytz.utc)
Dan
  • 1,536
  • 1
  • 10
  • 20