Home »
Python »
Python Reference »
Python datetime Class
Python datetime astimezone() Method with Example
Python datetime.astimezone() Method: Here, we are going to learn about the astimezone() method of datetime class in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on April 30, 2020
Python datetime.astimezone() Method
datetime.astimezone() method is used to manipulate objects of datetime class of module datetime.
It uses an instance of the class and returns a datetime object with new tzinfo attribute tz. It works on a datetime class instance.
Module:
import datetime
Class:
from datetime import datetime
Syntax:
astimezone(tz)
Parameter(s):
- tz - timezone information which should be changed.
Return value:
Returns a datetime object with new tzinfo attribute tz.
Example:
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