Saturday, December 28, 2024
Google search engine
HomeLanguagesPython datetime.utcoffset() Method with Example

Python datetime.utcoffset() Method with Example

The utcoffset() function is used to return a timedelta object that represents the difference between the local time and UTC time.

  • This function is used in used in the datetime class of module datetime.
  • Here range of the utcoffset is “timedelta(hours=24) <= offset <= timedelta(hours=24)”.
  • If the offset is east of UTC, then it is considered positive and if the offset is west of UTC, then it is considered negative. Since there are 24 hours in a day, -timedelta(24) and timedelta(24) are the largest values possible.

Syntax: utcoffset()

Parameters: This function does not accept any parameter.

Return values: This function returns a timedelta object representing the difference between the local time and UTC time.

Example 1: Here output is None because now() function returns date and time in UTC format, hence the difference between the local time i.e, returned by now() function and UTC time is none.

Python3




# Python3 code for getting
# the difference between the
# local time and UTC time
 
# Importing datetime and pytz module
from datetime import datetime
import pytz
 
# Calling the now() function to get
# current date and time
date_time = datetime.now()
 
# Calling the utcoffset() function
# over the above initialized datetime
print(date_time.utcoffset())


Output:

None

Example 2: Finding the offset of time

Python3




# Python3 code for getting
# the difference between the
# local time and UTC time
 
# Importing datetime and pytz module
from datetime import datetime
import pytz
 
# Calling the now() function to
# get current date and time
naive = datetime.now()
 
# adding a timezone
timezone = pytz.timezone("Asia/Kolkata")
aware1 = timezone.localize(naive)
 
# Calling the utcoffset() function
# over the above localized time
print("Time ahead of UTC by:", aware1.utcoffset())


Output:

Time ahead of UTC by: 5:30:00

Example 3: Finding time offset

Python3




# Python3 code for getting
# the difference between the
# local time and UTC time
 
# Importing datetime and pytz module
from datetime import datetime
import pytz
 
# Calling the now() function to
# get current date and time
naive = datetime.now()
 
# adding a timezone
timezone = pytz.timezone("Asia/Tokyo")
aware1 = timezone.localize(naive)
 
# Calling the utcoffset() function
# over the above localized time
print("Time ahead of UTC by:", aware1.utcoffset())


Output:

Time ahead of UTC by: 9:00:00

RELATED ARTICLES

Most Popular

Recent Comments