Saturday, November 16, 2024
Google search engine
HomeLanguagesPython DateTime astimezone() Method

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




# Python3 code for getting
# a datetime instance according
# to the specified time zone parameter tz
 
# Importing datetime module
import datetime
 
# Specifying Singapore timedelta and timezone
# object
sgtTimeDelta = datetime.timedelta(hours=5)
sgtTZObject = datetime.timezone(sgtTimeDelta,
                                name="SGT")
 
# Specifying a datetime along with Singapore
# timezone object
d1 = datetime.datetime(2021, 8, 4, 10,
                       00, 00, 00, sgtTZObject)
 
# Calling the astimezone() function over the above
# specified Singapore timezone
d2 = d1.astimezone(sgtTZObject)
 
# Printing a datetime instance as per the above
# specified Singapore timezone
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




# Python3 code for getting
# a datetime instance according
# to the specified time zone parameter tz
 
# Importing datetime module
import datetime
 
# Calling now() function to return
# current datetime
d1 = datetime.datetime.now()
 
# Calling the astimezone() function without
# any timezone parameter
d2 = d1.astimezone()
 
# Printing the local current date, time and
# timezone
print(format(d2))


Output:

2021-08-04 06:41:15.128046+00:00

RELATED ARTICLES

Most Popular

Recent Comments