In Python 3.9+: zoneinfo
to use the IANA time zone database:
In Python 3.9 or later, you can specify particular time zones using the standard library, using zoneinfo
, like this:
>>> import datetime
>>> from zoneinfo import ZoneInfo
>>> datetime.datetime.now(ZoneInfo("America/Los_Angeles"))
datetime.datetime(2020, 11, 27, 6, 34, 34, 74823, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles'))
zoneinfo
gets its database of time zones from the operating system. If the operating system doesn't have an IANA database of time zones, (notably Windows), then the information is retrieved from the first-party PyPI package tzdata
if available.
In Python 3.2 or later:
If you need to specify UTC as the time zone, the standard library provides support from this in Python 3.2 or later:
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2020, 11, 27, 14, 34, 34, 74823, tzinfo=datetime.timezone.utc)
You can also get a datetime that includes the local time offset using astimezone
:
>>> datetime.datetime.now(datetime.timezone.utc).astimezone()
datetime.datetime(2020, 11, 27, 15, 34, 34, 74823, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))
In Python 3.6 or later, you can shorten the last line to:
>>> datetime.datetime.now().astimezone()
datetime.datetime(2020, 11, 27, 15, 34, 34, 74823, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))
If you want a solution that uses only the standard library and that works in both Python 2 and Python 3, see jfs' answer.
datetime.now().astimezone()
since Python 3.6 – Catholicityfrom datetime import datetime, timezone; datetime.now(timezone.utc).astimezone()
– Trussdatetime.date
objects can't have an associated time zone, onlydatetime.datetime
objects can. So the question is aboutdatetime.datetime.today
, and not aboutdatetime.date.today
, which are different. I've edited the question to make this slightly clearer. – Rhodarhodamine