尝试使用datetime模块时出现此错误
似乎它无法识别我的时间格式
文件中使用的时间格式如下:
2015年1月17日星期六21:20:41 +0000
有人知道导致这个问题的原因吗?谢谢!
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'
&#13;
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)
&#13;
答案 0 :(得分:0)
指令time_str = str(f)
正在将对象f转换为str。所以在你的情况下,time_str的值是&lt; _io.TextIOWrapper name ='time.txt'mode ='r'coding ='utf8'&gt;
您可能想要阅读该文件:
time_str = f.readline()