試圖使用日期時間模塊,我得到這個錯誤時間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)
請參閱:如何創建最小,完整和可驗證示例。 http://stackoverflow.com/help/mcve – Tempux