【问题标题】:Convert unicode to datetime proper strptime format将 unicode 转换为 datetime 正确的 strptime 格式
【发布时间】:2014-02-04 18:18:14
【问题描述】:

我正在尝试将 unicode 对象转换为 datetime 对象。

我通读了文档:http://docs.python.org/2/library/time.html#time.strptime

试过了

datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%SZ') 

但我收到错误消息ValueError: time data '2014-01-15T01:35:30.314Z' does not match format '%Y-%m-%dT%H:%M:%SZ'

对什么是正确的格式有任何反馈吗?

我很感激时间和专业知识。

【问题讨论】:

  • 您正在阅读错误的文档。虽然time.strptime 和datetime.datetime.strptime 显然是相似 函数,但它们(在2.6+ 上)完全分开实现,并且有不同的列表说明它们可以处理的原因。 (time 只是调用您平台的 C 库;datetime 手动处理其他格式指令,即使您的平台没有。)

标签: python django datetime unicode strptime


【解决方案1】:

你可以解析微秒:

from datetime import datetime
date_posted = '2014-01-15T01:35:30.314Z'
datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%S.%fZ')

【讨论】:

  • 我认为如果平台没有,则手动制作datetime 处理%f 仅在 3.1+ 中添加,但看起来它也被向后移植到 2.6。不错。
【解决方案2】:

一种选择是让dateutil 完成这项工作:

>>> from dateutil import parser
>>> parser.parse('2014-01-15T01:35:30.314Z')
datetime.datetime(2014, 1, 15, 1, 35, 30, 314000, tzinfo=tzutc())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-08
    • 2012-03-27
    • 2012-10-17
    • 1970-01-01
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多