简体   繁体   English

将 Python ISO 日期时间转换为 Epoch

[英]Convert Python ISO datetime to Epoch

I wanted to convert the iso datetime into epoch format using python datetime library.我想使用 python datetime 库将 iso datetime 转换为纪元格式。

Below is my code, but it's not working.下面是我的代码,但它不起作用。

from datetime import datetime
epoch = datetime(1970, 1, 1)
last_updated_at = int((datetime.strptime('2020-10-16T09:29:26.580-07:00', '%Y-%m-%dT%H:%M:%S.%f %z') - epoch).total_seconds()) 

I'm getting below error我得到以下错误

ValueError: time data '2020-09-01T12:47:54.863-07:00' does not match format '%Y-%m-%dT%H:%M:%S.%f %z'

use fromisoformat and timestamp :使用fromisoformattimestamp

from datetime import datetime

last_updated_at = int(datetime.fromisoformat('2020-10-16T09:29:26.580-07:00').timestamp()) 
# last_updated_at
# 1602865766

btw.顺便提一句。 your strptime format is nearly correct, just a space too much.您的 strptime 格式几乎正确,只是空格太多。 correct would have been '%Y-%m-%dT%H:%M:%S.%f%z' .正确的应该是'%Y-%m-%dT%H:%M:%S.%f%z'

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

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