[英]Converting string to datetime with milliseconds and timezone - Python
I have the following python snippet: 我有以下python片段:
from datetime import datetime
timestamp = '05/Jan/2015:17:47:59:000-0800'
datetime_object = datetime.strptime(timestamp, '%d/%m/%y:%H:%M:%S:%f-%Z')
print datetime_object
However when I execute the code, I'm getting the following error: 但是,当我执行代码时,我收到以下错误:
ValueError: time data '05/Jan/2015:17:47:59:000-0800' does not match format '%d/%m/%y:%H:%M:%S:%f-%Z'
what's wrong with my matching expression? 我的匹配表达式出了什么问题?
EDIT 2: According to this post , strptime
doesn't support %z
(despite what the documentation suggests). 编辑2:根据这篇文章 ,
strptime
不支持%z
(尽管文档建议)。 To get around this, you can just ignore the timezone adjustment?: 为了解决这个问题,您可以忽略时区调整?:
from datetime import datetime
timestamp = '05/Jan/2015:17:47:59:000-0800'
# only take the first 24 characters of `timestamp` by using [:24]
dt_object = datetime.strptime(timestamp[:24], '%d/%b/%Y:%H:%M:%S:%f')
print(dt_object)
Gives the following output: 给出以下输出:
$ python date.py
2015-01-05 17:47:59
EDIT: Your datetime.strptime
argument should be '%d/%b/%Y:%H:%M:%S:%f-%z'
编辑:您的
datetime.strptime
参数应为'%d/%b/%Y:%H:%M:%S:%f-%z'
With strptime()
, %y
refers to 使用
strptime()
, %y
指的是
Year without century as a zero-padded decimal number
没有世纪的年份为零填充十进制数
Ie 01
, 99
, etc. 即
01
, 99
,等等。
If you want to use the full 4-digit year, you need to use %Y
如果要使用完整的4位数年份,则需要使用
%Y
Similarly, if you want to use the 3-letter month, you need to use %b
, not %m
同样,如果您想使用3个字母的月份,则需要使用
%b
,而不是%m
I haven't looked at the rest of the string, but there are possibly more mismatches. 我没有查看字符串的其余部分,但可能存在更多不匹配。 You can find out how each section can be defined in the table at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
您可以在https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior的表格中找到每个部分的定义方式。
UTC偏移量为小写z。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.