Skip to content

Instantly share code, notes, and snippets.

@anentropic
Created July 7, 2025 13:28
Show Gist options
  • Save anentropic/01ab7dfaa56138593b12df0f2a26365c to your computer and use it in GitHub Desktop.
Save anentropic/01ab7dfaa56138593b12df0f2a26365c to your computer and use it in GitHub Desktop.
TZ name from country code and non-DST UTC offset
import pytz
from datetime import datetime, timedelta
def get_timezone_name(country_code: str, utc_offset_hours: float) -> str | None:
"""
Returns an IANA timezone name for the given country code and UTC offset.
(Best effort)
Parameters:
- country_code (str): ISO 3166 country code (e.g., 'DE').
- utc_offset_hours (int or float): UTC offset in hours (e.g., 1 for UTC+1).
Returns:
- str or None: Matching timezone name or None if no match is found.
"""
tz_names = pytz.country_timezones.get(country_code.upper())
if not tz_names:
return None # No timezones found for the country code
# candidate non-DST comparison dates
north_winter = datetime(2020, 1, 1)
south_winter = datetime(2020, 6, 1)
for tz_name in tz_names:
tz = pytz.timezone(tz_name)
standard_date = north_winter if tz.dst(south_winter) else south_winter
localized_date = tz.localize(standard_date)
offset = localized_date.utcoffset()
if offset is not None:
offset_hours = offset.total_seconds() / 3600
# Return the first matching timezone
if offset_hours == utc_offset_hours:
return tz_name
# if bad utc offset was given just return first tz for the country
return tz_names[0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment