2015-12-10 43 views
0

試圖使用日期時間模塊,我得到這個錯誤時間A%B%d%H不符合格式「%:

看來,它不承認我的時間格式

的時間格式在文件中使用的是這樣的:

週六1月17日21時20分41秒+0000 2015年

有誰知道是什麼原因導致這個問題?謝謝!

Traceback (most recent call last): 
 
    File "ttrends.py", line 46, in <module> 
 
    week = time_str_to_weekday(time_str, parse_time_format=parse_time_format) 
 
    File "ttrends.py", line 36, in time_str_to_weekday 
 
    dt = datetime.fromtimestamp(time.mktime(time.strptime(time_str, parse_time_format))) 
 
    File "c:\python34\lib\_strptime.py", line 494, in _strptime_time 
 
    tt = _strptime(data_string, format)[0] 
 
    File "c:\python34\lib\_strptime.py", line 337, in _strptime 
 
    (data_string, format)) 
 
ValueError: time data "<_io.TextIOWrapper name='time.txt' mode='r' encoding='utf8'>" does not match format '%a %b %d %H: 
 
%M:%S +0000 %Y'

parse_time_format = '%a %b %d %H:%M:%S +0000 %Y' 
 
day_output_date_format = '%Y%m%d_%a' 
 
month_output_date_format = '%Y%m' 
 
week_output_date_format = '%Y_%U' 
 

 
import time 
 
from datetime import datetime, timedelta 
 

 
with open("time.txt",'r',encoding='utf8') as f: 
 
    time_str = str(f) 
 

 
def time_str_to_day(time_str): 
 

 
    t = time.strptime(time_str, parse_time_format) 
 

 
    return time.strftime(day_output_date_format, t) 
 

 
def time_str_to_month(time_str): 
 

 
    t = time.strptime(time_str, parse_time_format) 
 

 
    return time.strftime(month_output_date_format, t) 
 

 
def time_str_to_week(time_str, parse_time_format=parse_time_format): 
 

 
    t = time.strptime(time_str, parse_time_format) 
 

 
    return time.strftime(week_output_date_format, t) 
 

 
#week starts on Monday 
 
def time_str_to_weekday(time_str, parse_time_format=parse_time_format): 
 
    dt = datetime.fromtimestamp(time.mktime(time.strptime(time_str, parse_time_format))) 
 

 
    week = [] 
 
    start = dt - timedelta(days = dt.weekday()) 
 

 
    for i in range(7): 
 
     current = start + timedelta(days = i) 
 
     week.append(current.strftime(day_output_date_format)) 
 
    #end = start + timedelta(days = 6) 
 
    return week 
 
week = time_str_to_weekday(time_str, parse_time_format=parse_time_format) 
 
print (week)

+0

請參閱:如何創建最小,完整和可驗證示例。 http://stackoverflow.com/help/mcve – Tempux

回答

0

指令time_str = str(f)正在改變對象f,成STR。所以你的情況time_str的值是< _io.TextIOWrapper名=「TIME.TXT」模式=「R」編碼=「utf-8」>

你可能想讀而不是文件:

time_str = f.readline() 
+0

感謝名單@Dav它固定的問題,但現在它給這個錯誤 '回溯(最近通話最後一個): 文件「ttrends.py」 46行,在 (time_str,parse_time_format = parse_time_format) 文件「c:\」在文件「 python34 \ lib \ _strptime.py「第494行_strptime_time tt = _strptime(data_string,format)[0] 文件」c:\ python34 \ lib \ _strptime.py「,第340行,位於_strptime data_string [found .end():]) ValueError:unconv對應的數據仍然是:' – Robbert

相關問題