8

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)
Ender2050
  • 6,912
  • 12
  • 51
  • 55
  • 1
    My guess is that UTC being the universal time format originating over London, this is also where it defaults its values to. Everyone is counting from "0", so it makes sense for it to default to it. I get the question, but it would probably create more problems if no one really knew what it defaults to in terms of offset, especially if you run it on different platforms. – Torxed Sep 28 '17 at 20:45
  • 1
    probably because `pytz` is third-party. IMO utc datetime objs are the only ones acceptable to have as naive, so a better question would be why `datetime.now()` does not have the local tz info attached. – wim Sep 28 '17 at 20:50
  • thanks for the third party note - didn't realize `timezone.utc` was available. – Ender2050 Sep 29 '17 at 02:35

1 Answers1

2

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

Sam Hartman
  • 6,210
  • 3
  • 23
  • 40