datetime.datetime.utcnow()
Why does this datetime not have any timezone info given that it is explicitly a UTC datetime?<
The standard Python libraries don't include any tzinfo classes (but see pep 431). I can only guess at the reasons. Personally I think it was a mistake not to include a tzinfo class for UTC, because that one is uncontroversial enough to have a standard implementation.
Edit: Although there's no implementation in the library, there is one given as an example in the tzinfo documentation.
from datetime import timedelta, tzinfo
ZERO = timedelta(0)
# A UTC class.
class UTC(tzinfo):
"""UTC"""
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
To use it, to get the current time as an aware datetime object:
from datetime import datetime
now = datetime.now(utc)
There is datetime.timezone.utc in Python 3.2+:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)