简体   繁体   中英

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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