Search code examples
pythondatetimeepochpytz

Convert EST, CST and DST timezones to unix timestamp in Pytz Module in Python 3


I have a date that comes in the following format:

2019-12-13 20:18 EST or 2019-12-13 20:18 DSTor 2019-12-13 20:18 CST

I would like to convert them to unix timestamp.

I am using Pytz module.

So far, I have tried using datetime module in the following way:

time_est = '2019-12-13 20:18 EST'

datetime.datetime.strptime(time_est, '%Y-%m-%d %H:%M %z')

This does not seem to work either. Any suggestions out there or tips would be appreciated.


Solution

  • Time zone name abbreviations are ambiguous in many cases (one abbreviation for different time zones, see e.g. here), so it is best to explicitly define what your abbreviations mean. You can do so by supplying a mapping dict to dateutil's parser.

    import dateutil
    
    tzmapping = {'EST': dateutil.tz.gettz('America/New_York'),
                 'EDT': dateutil.tz.gettz('America/New_York'),
                 'CST': dateutil.tz.gettz('America/Chicago'),
                 'CDT': dateutil.tz.gettz('America/Chicago')
                 # add more if needed...}
    
    time_eastern = '2019-12-13 20:18 EST'
    
    dtobj = dateutil.parser.parse(time_eastern, tzinfos=tzmapping)
    # datetime.datetime(2019, 12, 13, 20, 18, tzinfo=tzfile('US/Eastern'))
    
    time_unix = dtobj.timestamp()
    # 1576286280.0
    

    If you must use pytz, you'll have to ignore EST in the string, parse to naive datetime, localize to the appropriate time zone and then take the timestamp:

    import datetime
    import pytz
    
    eastern = pytz.timezone('America/New_York')
    dtobj = eastern.localize(datetime.datetime.strptime(time_eastern, '%Y-%m-%d %H:%M EST'))
    time_unix = dtobj.timestamp()
    # 1576286280.0