Python datetime.tzname() Method with Example
Last Updated :
23 Aug, 2021
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
from datetime import datetime
import pytz
dt = datetime.now()
print (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
from datetime import datetime
import pytz
dt = datetime.now()
print (dt)
print (dt.tzinfo)
print ( "Timezone:" , dt.tzname())
print ()
timezone = pytz.timezone( "Asia/Kolkata" )
mydt = timezone.localize(dt)
print (mydt)
print ( "Tzinfo:" , mydt.tzinfo)
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
from datetime import datetime
import pytz
dt = datetime.now()
print (dt)
print (dt.tzinfo)
print ( "Timezone:" , dt.tzname())
print ()
timezone = pytz.timezone( "Asia/Tokyo" )
mydt = timezone.localize(dt)
print (mydt)
print ( "Tzinfo:" , mydt.tzinfo)
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
Share your thoughts in the comments
Please Login to comment...