Python DateTime astimezone() Method
The astimezone() function is used to return a DateTime instance according to the specified time zone parameter tz.
Note: The returned DateTime instance is having the new UTC offset value as per the tz parameter. And If this function does not take parameter tz, then the returned DateTime object will have the local date, time, and time zone.
Syntax: astimezone(tz=None)
Parameters: This function accepts an optional parameter that is illustrated below:
- tz: This is the specified timezone.
Return values: This function returns a datetime instance according to the specified time zone parameter tz. If the parameter tz is not specified then this function returns the local date, time and the time zone.
Example 1: In the below example, astimezone() function is taking the Singapore time zone object as its parameter. The Singapore timedelta() function is taking 5 hours as its parameter and its returned value is taken as the parameter of timezone() function. In this way, a DateTime along with Singapore timezone object is initialized for the function astimezone() to return its corresponding datetime instance.
Python3
import datetime
sgtTimeDelta = datetime.timedelta(hours = 5 )
sgtTZObject = datetime.timezone(sgtTimeDelta,
name = "SGT" )
d1 = datetime.datetime( 2021 , 8 , 4 , 10 ,
00 , 00 , 00 , sgtTZObject)
d2 = d1.astimezone(sgtTZObject)
print ( "Singapore time from a datetime instance:{}" . format (d2))
|
Output:
Singapore time from a datetime instance:2021-08-04 10:00:00+05:00
Example 2: In the below example, the astimezone() function does not accept any parameter, so this function returns the DateTime object having the local current date, time and the time zone. Here current date, time, and time zone are returned because of the datetime.now() function.
Python3
import datetime
d1 = datetime.datetime.now()
d2 = d1.astimezone()
print ( format (d2))
|
Output:
2021-08-04 06:41:15.128046+00:00
Last Updated :
02 Sep, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...