Search code examples
pythondateunix-timestamp

How to convert date given as a string into a unix time stamp, including the time zone, and the month is given as a abbreviaton


I have the following string:

08 Jan 2018 08:45:30 +0100

which I would like to conert to a unix timestamp. I know how to convert a time from this answer Convert string date to timestamp in Python , however this only describes how to do it if the name is given as a number like 01/12/1991. Furthermore, I do not know how to include the timezoen (+0100) into the conversion.

For the month I would have come up with a look up table which is a workaround, and I thought there may be a better way to do this

Here is the code I came up with for that:

lookup = {}


lookup['Jan'] = '01'
lookup['Feb'] = '02'
lookup['Mar'] = '03'
lookup['Apr'] = '04'
lookup['Mai'] = '05'
lookup['Jun'] = '06'
lookup['Jul'] = '07'
lookup['Aug'] = '08'
lookup['Sep'] = '09'
lookup['Okt'] = '10'
lookup['Nov'] = '11'
lookup['Dec'] = '12'

dates_to_convert = '08 Jan 2018 08:45:30 +0100'


dates_to_convert.replace(dates_to_convert.split()[1],lookup[dates_to_convert.split()[1]])

## Now continue with solution from linked answer...

Solution

  • If you were to look at the datetime.strptime() documentation on patterns, you'll see that the %b pattern matches abbreviated month names, and %z handles a timezone offset:

    %b Month as locale’s abbreviated name.

    [...]

    %z UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).

    Unless you set a locale, the default C locale matches US month names out of the box.

    For your string, the pattern is %d %b %Y %H:%M:%S %z:

    >>> from datetime import datetime
    >>> dates_to_convert = '08 Jan 2018 08:45:30 +0100'
    >>> datetime.strptime(dates_to_convert, '%d %b %Y %H:%M:%S %z')
    datetime.datetime(2018, 1, 8, 8, 45, 30, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))