Home »
Python »
Python Reference »
Python datetime Class
Python datetime utcoffset() Method with Example
Python datetime.utcoffset() Method: Here, we are going to learn about the utcoffset() method of datetime class in Python with its definition, syntax, and examples.
Submitted by Hritika Rajput, on April 30, 2020
Python datetime.utcoffset() Method
datetime.utcoffset() method is used in the datetime class of module datetime.
It uses an instance of the class and returns a timedelta instance corresponding to UTC offset of the tzinfo specified in the instance given.
Module:
import datetime
Class:
from datetime import datetime
Syntax:
utcoffset()
Parameter(s):
Return value:
The return type is a timedelta object representing the difference between the local time and UTC time.
Range of the utcoffset: -timedelta(hours=24) <= offset <= timedelta(hours=24)
If the offset is east of UTC, then it is considered positive and if it is west of UTC, it is negative. Since there are 24 hours in a day, -timedelta(24) and timedelta(24) are the largest values possible.
Example:
from datetime import datetime
import pytz
naive= datetime.now()
## Tzinfo is missing from the time object
## which is naive
print(naive)
print(naive.tzinfo)
print(naive.utcoffset())
print()
## Adding a timezone
timezone = pytz.timezone("Asia/Kolkata")
aware1 = timezone.localize(naive)
print(aware1)
print(aware1.tzinfo)
print("Time ahead of UTC by:", aware1.utcoffset())
print()
## After adding the timezone info,
## the object it becomes aware
timezone = pytz.timezone("Asia/Tokyo")
aware2 = timezone.localize(naive)
print(aware2)
print(aware2.tzinfo)
print("Time ahead of UTC by:", aware2.utcoffset())
print()
timezone = pytz.timezone("America/New_York")
aware3 = timezone.localize(naive)
print(aware3)
print(aware3.tzinfo)
## timedelta comes as -1 day 20 hrs
## which is equal to -4 hrs
print("Time behind to UTC by:", aware3.utcoffset())
print()
## You can also use the astimezone
## function of datetime to
timezone = pytz.timezone("Europe/Berlin")
aware4 = naive.astimezone(timezone)
print(aware4)
print(aware4.tzinfo)
print("Time ahead of UTC by:", aware4.utcoffset())
Output
2020-04-30 20:35:51.516509
None
None
2020-04-30 20:35:51.516509+05:30
Asia/Kolkata
Time ahead of UTC by: 5:30:00
2020-04-30 20:35:51.516509+09:00
Asia/Tokyo
Time ahead of UTC by: 9:00:00
2020-04-30 20:35:51.516509-04:00
America/New_York
Time behind to UTC by: -1 day, 20:00:00
2020-04-30 22:35:51.516509+02:00
Europe/Berlin
Time ahead of UTC by: 2:00:00