pythondatetimetimezone

Get timezone for specific date


I have a list of dates formatted like so:

'2024-01-01`

I need to turn them into ISO datetimes like so:

`2024-01-01T00:00:00-08:00`

I thought this would be easy, I was wrong. I've seen many questions talk about this on SO, but they tend to over look the complexity of daylight savings time (DST).

What can't be used in a solution:

   datetime.now()

Using datetime.now() will give the current timezone, on the date it is today, and will not be relevant to the date in question.

I need to return the proper offest, when converting a specific date, based on what the offset would have been in local time at the date in question. Example:

'2024-01-01' # becomes
'2024-01-01T00:00:00-08:00'

'2024-06-06' # becomes
'2024-01-01T00:00:00-07:00'

I have a solution to brute force this by calculating daylight savings time start and finishes. But that's an ugly solution, there has to be some manipulation of the datetime api that works better.


Solution

  • from datetime import datetime
    import pytz
    
    def get_iso_datetime_with_timezone(date_str):
        date_obj = datetime.strptime(date_str, '%Y-%m-%d')
    
        aware_datetime_utc = pytz.utc.localize(date_obj)
    
        timezone = pytz.timezone('America/Los_Angeles')  # Example timezone, replace with your desired timezone
    
        aware_datetime_timezone = aware_datetime_utc.astimezone(timezone)
    
        iso_datetime_with_timezone = aware_datetime_timezone.strftime('%Y-%m-%dT%H:%M:%S%z')
    
        return iso_datetime_with_timezone
    
    dates = ['2024-01-01', '2024-06-06']
    
    for date_str in dates:
        iso_datetime_with_timezone = get_iso_datetime_with_timezone(date_str)
        print(f'{date_str} => {iso_datetime_with_timezone}')}
    

    ensure you replace 'America/Los_Angeles' with the appropriate timezone for your use case you can find the list of supported timezones in the pytz documentation pytz handles historical timezone data so it will correctly account for DST changes on the specified date

    NES ANSWER

    from datetime import datetime
    from zoneinfo import ZoneInfo
    
    def get_iso_datetime_with_timezone(date_str, tz_name='America/Los_Angeles'):
        # Parse input date string to naive datetime object
        date_obj = datetime.strptime(date_str, '%Y-%m-%d')
        
        aware_datetime = date_obj.replace(tzinfo=ZoneInfo(tz_name))
        
        iso_datetime_with_timezone = aware_datetime.isoformat()
        
        return iso_datetime_with_timezone
    
    
    dates = ['2024-01-01', '2024-06-06']
    
    for date_str in dates:
        iso_datetime_with_timezone = get_iso_datetime_with_timezone(date_str)
        print(f'{date_str} => {iso_datetime_with_timezone}')