如何将以字符串形式给出的日期转换为 unix 时间戳,包括时区,月份以缩写形式给出

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

我有以下字符串:

08 Jan 2018 08:45:30 +0100

我想将其转换为 unix 时间戳。我知道如何从这个答案 Convert string date to timestamp in Python 转换时间,但是这仅描述了如果名称以 01/12/1991 之类的数字形式给出时如何进行。此外,我不知道如何将 timezoen (+0100) 包含到转换中。

这个月我会想出一个解决方法 table,我认为可能有更好的方法来做到这一点

这是我为此想出的代码:

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...

如果您查看 datetime.strptime() documentation on patterns,您会看到 %b 模式匹配缩写的月份名称,并且 %z 处理时区偏移:

%b Month as locale’s abbreviated name.

[...]

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

除非您设置语言环境,否则默认的 C 语言环境会立即匹配美国月份名称。

对于您的字符串,模式是 %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)))

您可以结合 datetime.strptime 来解析您的字符串,并结合 datetime.timestamp 来输出 UNIX 时间戳

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

像这样的东西应该可以工作:

from datetime import datetime

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

如果只需要整数部分(秒):

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