Skip to main content
 首页 » 编程设计

Python datetime.strptime之解析复杂的字符串

2024年10月24日35zhenyulu

我想根据字符串“2015-06-29T11:55:30.000000Z”创建日期时间。

我试过:

import datetime 
print datetime.datetime.strptime("2015-06-29T11:55:30.000000Z", "%y-%m-%dT%H:%M:%S.000000Z")    

我得到了以下错误:

Traceback (most recent call last): 
  File "x1.py", line 5, in <module> 
    print datetime.datetime.strptime(date, "%y-%m-%dT%H:%M:%S.000000Z")    
  File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime 
    (data_string, format)) 
ValueError: time data '2015-06-29T11:55:30.000000Z' does not match format '%y-%m-%dT%H:%M:%S.000000Z' 

我做错了什么?如何解析?

请您参考如下方法:

大写%Y:

import datetime as DT 
DT.datetime.strptime("2015-06-29T11:55:30.000000Z", "%Y-%m-%dT%H:%M:%S.000000Z")    
# datetime.datetime(2015, 6, 29, 11, 55, 30) 

%y 匹配两位数的年份 -- years without century as a decimal number year . %Y 匹配 4 位数年份。