Search code examples
pythondatedatetimetimezonepytz

Can Dates be Timezone-Aware in Python?


There's lots of SO answers on ensuring datetimes are a particular timezone. For example you can ensure your datetime is UTC with

from datetime import datetime
import pytz

now_utc = datetime.utcnow()

which yields:

datetime.datetime(2017, 5, 11, 17, 37, 5, 602054)

you can make that datetime aware of its timezone (e.g. for asserting two different datetime objects are from the same timezone) with

now_utc_aware = datetime.now(pytz.utc) 

datetime.datetime(2017, 5, 11, 17, 38, 2, 757587, tzinfo=< UTC>)

But when I pull the date from a timezone-aware datetime, I seem to lose the timezone-awareness.

now_utc_aware.date()

datetime.date(2017, 5, 11)

Interestingly, there's a SO question which seems to ask exactly this, and about a date specifically (datetime.today()), but the answers (including an accepted one) relate to datetimes. The code I've seen to add timezone awareness to datetimes all seem to throw errors on my datetime.date object.

Is it possible to add timezone awareness to a date object?


Solution

  • From the Python docs:

    class datetime.date
    An idealized naive date, ... Attributes: year, month, and day.

    There's nothing there for time or time zone. It's just a date.

    While it is true that not everywhere on Earth is on the same date simultaneously (because of time zones), that doesn't mean a date itself has time zone awareness.

    As a real-world analogy, think of a date as just a square on a calendar. One cannot start talking about timezones without introducing time, which is measured by a clock, not a calendar.