简体   繁体   English

如何将日期/时间字符串转换为纪元?

[英]How to convert date/time string to epoch?

Have the following string: 具有以下字符串:

"date Thursday June 03 12:02:56 2017"

What would be the proper way of convert it to epoch time? 将其转换为纪元时间的正确方法是什么?

You can use datetime.strptime() to parse your date and then just do delta with the epoch: 您可以使用datetime.strptime()来解析您的日期,然后仅对纪元进行增量操作:

from datetime import datetime as dt

epoch = dt(1970, 1, 1)
date = "date Thursday June 03 12:02:56 2017"

epoch_time = int((dt.strptime(date, "date %A %B %d %H:%M:%S %Y") - epoch).total_seconds())
# 1496491376

Another solution is to create a time.struct_time structure by parsing with time.strptime() and then pass it into calendar.timegm() to convert to epoch time. 另一种解决方案是通过使用time.strptime()解析来创建一个time.struct_time结构,然后将其传递到calendar.timegm()以转换纪元时间。

import time
import calendar
timestr = "date Thursday June 03 12:02:56 2017"
calendar.timegm(time.strptime(timestr, "date %A %B %d %H:%M:%S %Y"))
# returns 1496491376

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM