Python datetime utcoffset() Method with Example

Python datetime.utcoffset() Method: In this tutorial, we will learn about the utcoffset() method of datetime class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 22, 2023

Python datetime.utcoffset() Method

The datetime.utcoffset() method returns a timedelta instance corresponding to UTC offset of the tzinfo specified in the instance given.

Module

The following module is required to use utcoffset() method:

import datetime

Class

The following class is required to use utcoffset() method:

from datetime import datetime

Syntax

The following is the syntax of utcoffset() method:

utcoffset()

Parameter(s)

The following are the parameter(s):

  • None

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 of datetime utcoffset() Method in Python

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



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.