tzname() returns the name of the time zone as a string by calling self.tzinfo.tzname(self). For a naive datetime it returns None.
For the built-in timezone class, the name is the one you passed to timezone(offset, name); without a name Python generates 'UTC' for zero or 'UTC+HH:MM' otherwise. strftime() uses the same value for %Z.
datetime.tzname() is an instance method of datetime.datetime: call it on an existing object with dot notation, such as moment.tzname(...). Import the class first, for example from datetime import datetime. The time class has a method with the same name.
The name is only a label for people; Python never uses it in calculations.
Method signatures
python
datetime.tzname()
time.tzname()
tzinfo.tzname(dt) # implemented by tzinfo subclasses
# returns: str or None
Parameters
tzname() takes no parameters on datetime and time objects.
Return Value
Return Value
Description
str
The zone name or abbreviation reported by the tzinfo.
None
For naive values, or a tzinfo that returns None.
Python Examples
Example 1 — Compare tzname() with %Z
Print the name and the %Z text for a naive value, UTC, an unnamed offset, and a named offset.
python
from datetime import datetime, timedelta, timezone
zones = [None, timezone.utc, timezone(timedelta(hours=-8)), timezone(timedelta(hours=9), "JST")]
for zone in zones:
moment = datetime(2024, 3, 15, 10, 30, tzinfo=zone)
print(repr(moment.tzname()), repr(moment.strftime("%Z")))