Convert String date to long in python [duplicate]

╄→гoц情女王★ 提交于 2020-08-10 19:35:26

问题


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

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