I’m working on a problem where I need to get date times and get their UTC offset.
The data that I get is a date a time and longitude and latitude.
I am currently using pytz and timezonefinder to find the timezone and get utc offset
def get_utc_offset_from_obj(datetime_obj: datetime, timezone) -> str:
timezone = pytz.timezone(timezone)
localized_date = timezone.localize(datetime_obj)
offset = localized_date.utcoffset()
total_minutes = int(offset.total_seconds() / 60)
hours, minutes = divmod(abs(total_minutes), 60)
sign = '-' if total_minutes < 0 else '+'
formatted_offset = f"{sign}{hours:02d}:{minutes:02d}"
return formatted_offset
The problem is that apparently before 1967 US States didn’t have uniform DST so within the same timezone some states or counties may adopt daylight savings time and some may not. Which makes the code above not accurate.
For example Texas is part of the America/Chicago timezone but During the years from 1945 to 1966 it didn’t adopt Daylight savings time. If I would get the timezone from the coordinates then get the UTC offset it would give me that the timezone adopted DST.
I’m wondering if timezonefinder or pytz can give me the data I am looking for.
As I mentioned I tried converting geo coordinates into timezone then getting the offset from utc of that timezone on the specific date. It didn’t work because for the us specifically there were changes in the timezones where within the same timezone different states (sometimes even different counties within the same state) might choose to switch to dst and others won’t.
Dhia Ammar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.