在 Python 中将 ISO 8601 日期时间转换为秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27245488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:34:14  来源:igfitidea点击:

Converting ISO 8601 date time to seconds in Python

pythonpython-2.7timeiso8601rfc3339

提问by Zaynaib Giwa

I am trying to add two times together. The ISO 8601 time stamp is '1984-06-02T19:05:00.000Z', and I would like to convert it to seconds. I tried using the Python module iso8601, but it is only a parser.

我试图加在一起两次。ISO 8601 时间戳是“1984-06-02T19:05:00.000Z”,我想将其转换为秒。我尝试使用 Python 模块iso8601,但它只是一个解析器。

Any suggestions?

有什么建议?

采纳答案by heyitschun

If you want to get the seconds since epoch, you can use python-dateutilto convert it to a datetimeobject and then convert it so seconds using the strftimemethod. Like so:

如果您想获得自纪元以来的秒数,您可以使用python-dateutil将其转换为datetime对象,然后使用该strftime方法将其转换为秒数。像这样:

>>> import dateutil.parser as dp
>>> t = '1984-06-02T19:05:00.000Z'
>>> parsed_t = dp.parse(t)
>>> t_in_seconds = parsed_t.strftime('%s')
>>> t_in_seconds
'455047500'

So you were halfway there :)

所以你已经成功了一半 :)

回答by jfs

Your date is UTC time in RFC 3339 format, you could parse it using only stdlib:

您的日期是RFC 3339 格式的UTC 时间,您可以仅使用 stdlib 解析它:

from datetime import datetime

utc_dt = datetime.strptime('1984-06-02T19:05:00.000Z', '%Y-%m-%dT%H:%M:%S.%fZ')

# Convert UTC datetime to seconds since the Epoch
timestamp = (utc_dt - datetime(1970, 1, 1)).total_seconds()
# -> 455051100.0

See also Converting datetime.date to UTC timestamp in Python

另请参阅在 Python 中将 datetime.date 转换为 UTC 时间戳

How do I convert it back to ISO 8601 format?

如何将其转换回 ISO 8601 格式?

To convert POSIX timestamp back, create a UTC datetime object from it, and format it using .strftime()method:

要将 POSIX 时间戳转换回来,请从中创建一个 UTC 日期时间对象,并使用以下.strftime()方法对其进行格式化:

from datetime import datetime, timedelta

utc_dt = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
# -> 1984-06-02T19:05:00.000000Z

Note: It prints six digits after the decimal point (microseconds). To get three digits, see Formatting microseconds to 2 decimal places (in fact converting microseconds into tens of microseconds).

注意:它在小数点后打印六位数字(微秒)。要获得三位数字,请参阅将微秒格式化为 2 个小数位(实际上将微秒转换为几十微秒)

回答by toppk

Here is a solution in Python 3:

这是 Python 3 中的解决方案:

$ date +%s
1428030452
$ TZ=US/Pacific date -d @1428030452 '+%Y%m%d %H:%M:%S %z'
20150402 20:07:32 -0700
$ TZ=US/Eastern date -d @1428030452 '+%Y%m%d %H:%M:%S %z'
20150402 23:07:32 -0400
$ python3
>>> from datetime import datetime,timezone
>>> def iso2epoch(ts):
...     return int(datetime.strptime(ts[:-6],"%Y%m%d %H:%M:%S").replace(tzinfo=timezone.utc).timestamp()) - (int(ts[-2:])*60 + 60 * 60 * int(ts[-4:-2]) * int(ts[-5:-4]+'1'))
...
>>> iso2epoch("20150402 20:07:32 -0700")
1428030452
>>> iso2epoch("20150402 23:07:32 -0400")
1428030452
>>>