【问题标题】:Python - How to convert this timestamp format to datetime? [duplicate]Python - 如何将此时间戳格式转换为日期时间? [复制]
【发布时间】:2014-01-23 19:09:56
【问题描述】:

我有时间戳格式,例如“2014-01-06T00:39:45.001+0000”,但我不知道这个时间戳格式到底是什么。所以我无法将它转换为我想要的日期时间。

如何用 Python 转换它?

【问题讨论】:

  • @tback: 或者更具体地说,它是rfc 3339 中描述的 ISO 8601 配置文件(时间偏移中的+/-“:”)

标签: python datetime


【解决方案1】:

使用dateutil.parser.parse:

>>> import dateutil.parser
>>> dateutil.parser.parse("2014-01-06T00:39:45.001+0000")
datetime.datetime(2014, 1, 6, 0, 39, 45, 1000, tzinfo=tzutc())

【讨论】:

    【解决方案2】:

    您可以使用datetime.strptime(date_string, format) 解析任意格式的日期和时间,并使用here 提供的用于定义format 的语法。

    在这种情况下:

     format = "%Y-%m-%dT%H:%M:%S.%f%z"
    

    注意:%z 在 Python 3.2 之前不支持 .strptime() 方法。

    【讨论】:

    • 我想我没有!你是对的,但我在文档中看不到对该行为的引用; %z 的注释 (5) 没有提到它,尽管其他注释提到了差异。我将编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 2017-05-20
    • 2016-11-26
    • 1970-01-01
    • 2013-12-04
    • 2019-09-03
    • 2014-08-06
    • 1970-01-01
    • 2019-02-25
    相关资源
    最近更新 更多