Home »
Python »
Python Reference »
Python datetime Class
Python datetime astimezone() Method with Example
Python datetime.astimezone() Method: In this tutorial, we will learn about the astimezone() method of datetime class in Python with its usage, syntax, and examples.
By Hritika Rajput Last updated : April 22, 2023
Python datetime.astimezone() Method
The datetime.astimezone() method is used to get a datetime object with new tzinfo attribute tz. It works on a datetime class instance.
Module
The following module is required to use astimezone() method:
import datetime
Class
The following class is required to use astimezone() method:
from datetime import datetime
Syntax
The following is the syntax of astimezone() method:
astimezone(tz)
Parameter(s)
The following are the parameter(s):
The following are the parameter(s):
- tz - timezone information which should be changed.
Return Value
Returns a datetime object with new tzinfo attribute tz.
Example for datetime astimezone() Method in Python
from datetime import datetime
import pytz
naive= datetime.now()
## Tzinfo is missing from the time object
## which is naive
print("Tzinfo:",naive.tzinfo)
print()
## Adding a timezone
timezone = pytz.timezone("Asia/Kolkata")
aware1 = naive.astimezone(timezone)
print("Tzinfo:",aware1.tzinfo)
print()
## After adding the timezone info,
## the object it becomes aware
timezone = pytz.timezone("Asia/Tokyo")
aware2 = aware1.astimezone(timezone)
print("Initial tzinfo:",aware1.tzinfo)
print("Final tzinfo:",aware2.tzinfo)
print()
## No timezone was defined for naive
print(naive)
## Timezone changed from None to Asia/Kolkata
## for aware1 object
print(aware1)
## Timezone changed from Asia/Kolkata to
## Asia/Tokyo for aware2 object
print(aware2)
Output
Tzinfo: None
Tzinfo: Asia/Kolkata
Initial tzinfo: Asia/Kolkata
Final tzinfo: Asia/Tokyo
2020-04-30 18:44:12.784666
2020-05-01 00:14:12.784666+05:30
2020-05-01 03:44:12.784666+09:00