Converting ISO 8601 date time to seconds in Python

筅森魡賤 提交于 2019-11-29 11:50:37

问题


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.

Any suggestions?


回答1:


If you want to get the seconds since epoch, you can use python-dateutil to convert it to a datetime object and then convert it so seconds using the strftime method. Like so:

>>> 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 :)




回答2:


Your date is UTC time in RFC 3339 format, you could parse it using only 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

How do I convert it back to ISO 8601 format?

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

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




回答3:


Here is a solution in 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
>>>


来源:https://stackoverflow.com/questions/27245488/converting-iso-8601-date-time-to-seconds-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!