【问题标题】:Converting UTC-Date-String to Unixtimestamp [duplicate]将 UTC-Date-String 转换为 Unixtimestamp [重复]
【发布时间】:2018-06-12 22:45:42
【问题描述】:

我的日期格式如下:"2018-06-12T13:58:36.663550655Z"

我想将此字符串转换为 Unix 时间戳。

这是我的代码:

from datetime import datetime
    date = '2018-06-12T14:03:35.306662173Z'
    time = datetime.strptime(date,"%Y-%m-%dT%H:%M:%S.%fZ")
    unixTime = datetime.utcfromtimestamp(time)

运行时出现错误:

ValueError: 时间数据 '2018-06-12T14:03:35.306662173Z' 不匹配 格式 '%Y-%m-%dT%H:%M:%S.%fZ'

如果有人可以帮助我,那就太好了! 谢谢!

【问题讨论】:

  • 仅供参考,datetime.strptime() 返回一个 datetime 对象,而不是 posix 时间戳。
  • 我不确定,但我认为您需要time = datetime.strptime(date,"%Y-%m-%dT%H:%M:%S.%f%Z") 来处理时区标识符

标签: python python-3.x


【解决方案1】:

尝试去除多余的信息。

例如:

import time
from datetime import datetime
date = '2018-06-12T14:03:35.306662173Z'
d = datetime.strptime(date[:26],"%Y-%m-%dT%H:%M:%S.%f")
unixTime =  time.mktime(d.timetuple())
print(unixTime)

输出:

1528792415.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-05
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 2021-06-05
    • 2017-08-20
    • 2018-07-06
    相关资源
    最近更新 更多