Python datetime.tzname() Method with Example
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 modulefrom datetime import datetime # import pytz moduleimport pytz # get the datetime of the presentdt = datetime.now() # Tzinfo is missing from the time objectprint(dt) # display tz info for the dtprint(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 modulefrom datetime import datetime # import pytz moduleimport pytz # get the datetime of the presentdt = datetime.now() # Tzinfo is missing from the time objectprint(dt) # display tz info for the dtprint(dt.tzinfo)print("Timezone:", dt.tzname())print() # Adding a timezone for asia /kolkatetimezone = pytz.timezone("Asia/Kolkata") # getting the timezone using localize methodmydt = timezone.localize(dt) print(mydt) # getting the time zone info using tzinfo methodprint("Tzinfo:", mydt.tzinfo) # display time zone name using tznameprint("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 modulefrom datetime import datetime # import pytz moduleimport pytz # get the datetime of the presentdt = datetime.now() # Tzinfo is missing from the time objectprint(dt) # display tz info for the dtprint(dt.tzinfo)print("Timezone:", dt.tzname())print() # Adding a timezone for asia /Tokyotimezone = pytz.timezone("Asia/Tokyo") # getting the timezone using localize methodmydt = timezone.localize(dt) print(mydt) # getting the time zone info using tzinfo methodprint("Tzinfo:", mydt.tzinfo) # display time zone name using tznameprint("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






Please Login to comment...