Open In App

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.

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 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 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 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

Article Tags :