Home > Back-end >  Python: Incorrect UTC Offset
Python: Incorrect UTC Offset

Time:11-24

The following code prints: -1 day, 19:00:00 when New York is actually 5 hours behind UTC. What is wrong and how to fix it?

import pytz
from datetime import datetime

date = datetime(2022, 11, 23, 22, 30)
tz = pytz.timezone('America/New_York')
print(tz.utcoffset(date))

CodePudding user response:

tz.utcoffset(date) returns a datetime.timedelta that should be added to a UTC datetime to get local time. Its a negative number for negative UTC offsets so that the addition works.

>>> import pytz
>>> from datetime import datetime
>>> 
>>> date = datetime(2022, 11, 23, 22, 30)
>>> tz = pytz.timezone('America/New_York')
>>> offset = tz.utcoffset(date)
>>> offset
datetime.timedelta(days=-1, seconds=68400)
>>> date   offset
datetime.datetime(2022, 11, 23, 17, 30)

timedelta displays oddly. days=-1, seconds=68400 means to go backwards 1 day and then forward 68400 seconds, giving you that -5 hours.

CodePudding user response:

If you just want the offset as a string, you can use

date = datetime(2022, 11, 23, 22, 30, tzinfo = zoneinfo.ZoneInfo('America/New_York'))
print(date.strftime('%z'))

This prints: -0500

I'm using Python 3.9 - not sure if the syntax is the same in your version.

  • Related