2015-09-22 81 views
1

我想从一个txt文件中获取日期时间。在这个文件中,时间在其周围用[]表示。python datetime timestrp函数错误

我知道第一行总是一个时间戳。但是当我尝试使用strptime获取日期时间时,我收到一条错误消息。

我已经搜索了其他解决方案。但似乎没有发现任何与我的错误相符的东西。

代码:

FileYSI = open(FilenameYSI,'r') 
TimeStampYSI = [next(FileYSI)for x in xrange(1)] 

print TimeStampYSI[0] 
if TimeStampYSI[0][0] == '[' 
    TimeFP = time.strptime(TimeStampYSI[0],'[%y-%m-%d,%H:%M:%S.%f]\n') 

错误:

[2015-09-22,08:10:00.600000] 


Traceback (most recent call last): 
    File "C:/Users/brondert/Documents/realtime_data_aquadrone/trunk/src/MergeLogs.py", line 129, in <module> 
    MergeLogs("test") 
    File "C:/Users/brondert/Documents/realtime_data_aquadrone/trunk/src/MergeLogs.py", line 92, in MergeLogs 
    TimeFP = time.strptime(TimeStampYSI[0],'[%y-%m-%d,%H:%M:%S.600000]\n') 
    File "C:\Python27\lib\_strptime.py", line 467, in _strptime_time 
    return _strptime(data_string, format)[0] 
    File "C:\Python27\lib\_strptime.py", line 325, in _strptime 
    (data_string, format)) 
ValueError: time data '[2015-09-22,08:10:00.600000]\n' does not match format '[%y-%m-%d,%H:%M:%S.600000]\n' 
+0

的代码不匹配的错误消息'time.strptime(TimeStampYSI [0],'[%Y-%间 - %d,%H:%M :%S.600000] \ n')'不在你的代码中。 –

回答

5

4位数字的年份格式%Y(大写Y)不%y,你应该使用,与实施 -

TimeFP = time.strptime(TimeStampYSI[0],'[%Y-%m-%d,%H:%M:%S.%f]\n') 

演示 -

>>> import time 
>>> time.strptime('[2015-09-22,08:10:00.600000]\n','[%Y-%m-%d,%H:%M:%S.%f]\n') 
time.struct_time(tm_year=2015, tm_mon=9, tm_mday=22, tm_hour=8, tm_min=10, tm_sec=0, tm_wday=1, tm_yday=265, tm_isdst=-1) 

%y(小y)格式为2位数年。

另一件事,您正在使用time模块,你会得到一个struct_time作为strptime结果,但如果你想datetime,你应该使用datetime模块。示例 -

import datetime 
datetime.datetime.strptime(TimeStampYSI[0],'[%Y-%m-%d,%H:%M:%S.%f]\n') 
1

%y为2位数年份。对于4位必须使用%Y

TimeFP = time.strptime(TimeStampYSI[0],'[%Y-%m-%d,%H:%M:%S.%f]\n')