Python datetime.tzname() Method

Python datetime.tzname() Method

  1. Syntax of Python datetime.tzname() Method
  2. Example 1: Use the datetime.tzname() Method in Python
  3. Example 2: Find Details of a Specific Timezone Using the datetime.tzname() Method
  4. Example 3: Shorter Syntax of the datetime.tzname() Method

Python datetime.tzname() method is an efficient way of finding the time zone name of the datetime object passed. It is used in the DateTime class of module DateTime.

Syntax of Python datetime.tzname() Method

datetime.tzname()

Parameters

This method doesn’t accept any parameter.

Return

This method returns a string representing the time zone name of the datetime object passed.

Example 1: Use the datetime.tzname() Method in Python

from datetime import datetime

import pytz

datetime_object = datetime.now()

print(datetime_object)

print("Timezone:", datetime_object.tzname())

Output:

2022-08-30 17:25:40.919231
Timezone: None

The timezone of the current system is displayed. If the timezone is not set, then the output is None.

Example 2: Find Details of a Specific Timezone Using the datetime.tzname() Method

from datetime import datetime

import pytz

datetime_object = datetime.now()

timezone = pytz.timezone("Asia/Tokyo")

myTime = timezone.localize(datetime_object)

print("Date and time: ",myTime)

print("Tzinfo: ", myTime.tzinfo)

print("Timezone name: ", myTime.tzname())

Output:

Date and time:  2022-08-30 18:35:46.134498+09:00
Tzinfo:  Asia/Tokyo
Timezone name:  JST

You can easily enter any continent or country as the parameter of this method; this method will convert the time to the specified timezone.

For example, you can enter Europe / Berlin, and the time of the system will be converted to the current time in Berlin.

Example 3: Shorter Syntax of the datetime.tzname() Method

import datetime

import pytz

print(datetime.datetime.now(pytz.timezone('US/Pacific')))

Output:

2022-08-30 11:43:53.536388-07:00

A shorter syntax improves the efficiency of the code.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python DateTime

  • Python datetime.datetime.year Attribute
  • Python datetime.tzinfo Class
  • Python datetime.datetime.replace() Method
  • Python datetime.timezone Class
  • Python datetime.day() Method
  • Python Datetime.fromtimestamp() Method