Search code examples
pythondatetimeunixtimestamp

How can I convert datetime to unix timestamp in python


I have one date format "Mon, 15 Jun 2020 22:11:06 PT" I want to convert this format to unix timestamp.

I am using the following code ===>

news_date = datetime.strptime(news_date, '%a, %d %b %Y %H:%M:%S %Z')
news_date = calendar.timegm(news_date.utctimetuple())   

But gives the following error ===>

ValueError: time data 'Mon, 15 Jun 2020 22:11:06 PT' does not match format '%a, %d %b %Y %H:%M:%S %Z'

How can i solve it and get the unix timestamp from this?


Solution

  • 2024 edit:

    • general note: with Python 3.9+, use zoneinfo. no need for a 3rd party lib anymore.
    • dateutil-specific: dateutil's parser can be fed with a mapping of abbreviations to IANA time zone names, to parse abbreviations. Example.

    2020 answer:

    %Z can't parse the time zone abbreviation PT - I suggest you skip parsing it and add it "manually" instead:

    from datetime import datetime
    import dateutil
    
    news_date = "Mon, 15 Jun 2020 22:11:06 PT"
    
    # parse string without the timezone:
    news_date = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
    
    # add the timezone:
    news_date = news_date.replace(tzinfo=dateutil.tz.gettz('US/Pacific'))
    
    # extract POSIX (seconds since epoch):
    news_date_posix = news_date.timestamp()
    # 1592284266.0
    

    if you have multiple strings with different timezones, you could use a dict to map the abbreviations to time zone names, e.g.

    tzmapping = {'PT': 'US/Pacific'}
    news_date = "Mon, 15 Jun 2020 22:11:06 PT"
    # get appropriate timezone from string, according to tzmapping:
    tz = dateutil.tz.gettz(tzmapping[news_date.split(' ')[-1]])
    # parse string and add timezone:
    news_date_datetime = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
    news_date_datetime = news_date_datetime.replace(tzinfo=tz)