2015-09-22 80 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')