Python 将 unicode 转换为 datetime 正确的 strptime 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21151664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:11:17  来源:igfitidea点击:

Convert unicode to datetime proper strptime format

pythondjangodatetimeunicodestrptime

提问by bbrooke

I am trying to convert a unicode object to a datetime object.

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

I read through the documentation: http://docs.python.org/2/library/time.html#time.strptime

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

and tried

并尝试

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

but I get the error message ValueError: time data '2014-01-15T01:35:30.314Z' does not match format '%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'

Any feedback on what is the proper format?

关于什么是正确格式的任何反馈?

I appreciate the time and expertise.

我感谢时间和专业知识。

采纳答案by Velimir Mlaker

You can parse the microseconds:

您可以解析微秒:

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

回答by alecxe

One option is to let dateutildo the job:

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

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