问题
I have data frame which has a column full of date-time of format yyyy-mm-ddTHH:MM:SSS.000Z
For example, 2019-06-17T19:17:45.000Z. I want to convert this to long type (unix epoch time) in python.
How to do that?
Thanks!
(How do I parse an ISO 8601-formatted date? This question is abut parsing the string. I want to do a conversion and hence it is different)
回答1:
Use module time:
import calendar
import time
calendar.timegm(time.strptime('2019-06-17T19:17:45.000Z', '%Y-%m-%dT%H:%M:%S.%fZ'))
Output: 1560799065
回答2:
using datetime module, fromisoformat (most likely fastest option) to parse the string and timestamp() to get POSIX seconds since the epoch:
from datetime import datetime
s = '2019-06-17T19:17:45.000Z'
ts = datetime.fromisoformat(s.replace('Z', '+00:00')).timestamp()
# 1560799065.0
or strptime with appropriate format code:
ts = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z').timestamp()
...or dateutil's parser.parse (slower but even more convenient):
from dateutil.parser import parse
ts = parse(s).timestamp()
来源:https://stackoverflow.com/questions/63030181/convert-string-date-to-long-in-python