0

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...
Kev1n91
  • 3,553
  • 8
  • 46
  • 96

2 Answers2

2

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)))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

You can combine datetime.strptime to parse your string and datetime.timestamp to output a UNIX timestamp

https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime
https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp

Something like this should work:

from datetime import datetime

datetime.strptime('08 Jan 2018 08:45:30 +0100', '%d %b %Y %H:%M:%S %z').timestamp()
>>> 1515397530.0

If you want the integer part only (seconds):

timestamp = datetime.strptime('08 Jan 2018 08:45:30 +0100', '%d %b %Y %H:%M:%S %z').timestamp()
timestamp = int(timestamp)
>>> 1515397530
JoseKilo
  • 2,343
  • 1
  • 16
  • 28