ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.