Why does datetime.utcnow() return a naive datetime?

Viewed 2149

Concept question. Why does datetime.utcnow() return a naive date:

from datetime import datetime
datetime.utcnow()

instead of the time with UTC timezone specified like this:

from datetime import datetime, timezone
datetime.utcnow().replace(tzinfo=timezone.utc)

The datetime.py source indicates this is on purpose.

@classmethod
def utcnow(cls):
    "Construct a UTC datetime from time.time()."
    t = _time.time()
    return cls.utcfromtimestamp(t)

@classmethod
    def utcfromtimestamp(cls, t):
        """Construct a naive UTC datetime from a POSIX timestamp."""
        return cls._fromtimestamp(t, True, None)

Trying to learn the thinking behind it. Thank you.

Edit: From the linked question here (thank you) this appears to be the preferred approach in Python 3.2+:

from datetime import datetime, timezone
datetime.datetime.now(datetime.timezone.utc)
1 Answers

As far as I can tell this is so you can hurt yourself a lot, or at least I've found that particular decision has caused me no end of pain. I think the issue is that Python as shipped really only has support for UTC timezones and not for local timezones. The thinking seems to be that a lot of people will want to use naive dates for everything and keep track (possibly based on what program it is) whether it is UTC or local. so, involving timezones at all is an explicit decision that you as a programmer must take and unless you do that you'll never get a DateTime with a timezone.

Unfortunately, this decision combined with the idea that when converting (to posix times, naive datetimes are treated as local can lead to a lot of confusion. I've discussed some of the issues that came up for me here

Related