Search code examples
pythonstrptime

How to use strptime to extract local dates?


I am given datetimes recorded in America/Chicago in %m/%d/%Y %I:%M:%S %p format (i.e. 06/18/2019 09:30:00 PM). How can I transform these to datetime objects that recognise the local timezone/DST?

I tried datetime.strptime('06/18/2019 09:30:00 PM', '%m/%d/%Y %I:%M:%S %p').astimezone(timezone('America/Chicago')) which gave unexpected results (i.e. 2019-06-18 21:30:00+01:00 as opposed to 2019-06-18 21:30:00-05:00).

I was contemplating to augment the string (i.e. by adding "EST" or similar to it). This would, however, leave it to me to determine whether DST was in effect at the time or not.


Solution

  • you can use datetime.replace method to replace the tzinfo:

    ex = '06/18/2019 09:30:00 PM'
    
    
    extracted_datetime = datetime.strptime(ex, '%m/%d/%Y %I:%M:%S %p')
    my_tz = timezone('America/Chicago')
    
    print(extracted_datetime.replace(tzinfo=my_tz))