Open In App

Python datetime.tzname() Method with Example

Last Updated : 23 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

tzname() method is used in the DateTime class of module DateTime. This method is used to return the time zone name of the DateTime object passed, as a string.

Syntax:

tzname()

Return type:

It will return the time zone name of the DateTime object passed, as a string.

So first we need to import the module DateTime, and to get the timezone of the exact place we will simply pass the DateTime stamp generated by datetime.now() function to the tzname() function.

Example 1: Python program that will return the tzinfo() which is none

Python3




# import datetime module
from datetime import datetime
  
# import pytz module
import pytz
  
# get the datetime of the present
dt = datetime.now()
  
# Tzinfo is missing from the time object
print(dt)
  
# display tz info for the dt
print(dt.tzinfo)
print("Timezone:", dt.tzname())
print()


Output:

2021-08-06 02:58:15.162869

None

Timezone: None

It is also possible to get the timezone of some other place by explicitly adding the timezone. 

Example 2: Python program to add timezone for Asia/Kolkata and get the timezone details

Python3




# import datetime module
from datetime import datetime
  
# import pytz module
import pytz
  
# get the datetime of the present
dt = datetime.now()
  
# Tzinfo is missing from the time object
print(dt)
  
# display tz info for the dt
print(dt.tzinfo)
print("Timezone:", dt.tzname())
print()
  
# Adding a timezone for asia /kolkate
timezone = pytz.timezone("Asia/Kolkata")
  
# getting the timezone using localize method
mydt = timezone.localize(dt)
  
print(mydt)
  
# getting the time zone info using tzinfo method
print("Tzinfo:", mydt.tzinfo)
  
# display time zone name using tzname
print("Timezone name:", mydt.tzname())


Output:

2021-08-06 03:00:44.949286

None

Timezone: None

2021-08-06 03:00:44.949286+05:30

Tzinfo: Asia/Kolkata

Timezone name: IST

Example 3: Getting the timezone details for asia/Tokyo

Python3




# import datetime module
from datetime import datetime
  
# import pytz module
import pytz
  
# get the datetime of the present
dt = datetime.now()
  
# Tzinfo is missing from the time object
print(dt)
  
# display tz info for the dt
print(dt.tzinfo)
print("Timezone:", dt.tzname())
print()
  
# Adding a timezone for asia /Tokyo
timezone = pytz.timezone("Asia/Tokyo")
  
# getting the timezone using localize method
mydt = timezone.localize(dt)
  
print(mydt)
  
# getting the time zone info using tzinfo method
print("Tzinfo:", mydt.tzinfo)
  
# display time zone name using tzname
print("Timezone name:", mydt.tzname())


Output:

2021-08-06 03:02:02.569770

None

Timezone: None

2021-08-06 03:02:02.569770+09:00

Tzinfo: Asia/Tokyo

Timezone name: JST



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads