Python datetime tzname() Method with Example

Python datetime.tzname() Method: In this tutorial, we will learn about the tzname() method of datetime class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 22, 2023

Python datetime.tzname() Method

The datetime.tzname() method returns the time zone name of the datetime object passed as a string.

Module

The following module is required to use tzname() method:

import datetime

Class

The following class is required to use tzname() method:

from datetime import datetime

Syntax

The following is the syntax of tzname() method:

tzname()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

Returns the time zone name of the datetime object passed, as a string.

Example of datetime tzname() Method in Python

from datetime import datetime
import pytz

naive= datetime.now()
## Tzinfo is missing from the time object 
## which is naive 
print(naive)
print(naive.tzinfo)
print("Timezone for a naive object:", naive.tzname())
print()

## Adding a timezone
timezone = pytz.timezone("Asia/Kolkata")
aware1 = timezone.localize(naive)
print(aware1)
print("Tzinfo:",aware1.tzinfo)
print("Timezone name:", aware1.tzname())
print()

## After adding the timezone info, 
## the object it becomes aware
timezone = pytz.timezone("Asia/Tokyo")
aware2 = timezone.localize(naive)
print("Tzinfo:",aware2.tzinfo)
print("Timezone name:", aware2.tzname())
print()

timezone = pytz.timezone("America/New_York")
aware3 = timezone.localize(naive)
print("Tzinfo:",aware3.tzinfo)
## timedelta comes as -1 day 20 hrs 
## which is equal to -4 hrs 
print("Timezone name:", aware3.tzname())
print()

## You can also use the astimezone function
## of  datetime to 
timezone = pytz.timezone("Europe/Berlin")
aware4 = naive.astimezone(timezone)
print("Tzinfo:",aware4.tzinfo)
print("Timezone name:", aware4.tzname())

Output

2020-04-30 20:20:30.748312
None
Timezone for a naive object: None

2020-04-30 20:20:30.748312+05:30
Tzinfo: Asia/Kolkata
Timezone name: IST

Tzinfo: Asia/Tokyo
Timezone name: JST

Tzinfo: America/New_York
Timezone name: EDT

Tzinfo: Europe/Berlin
Timezone name: CEST




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.