我刚刚参加了Udacity的数据分析课程。 我的代码是:
enrollments_filename= '/Users/abc/Desktop/Udacity - Intro to Data Analysis/enrollments.csv'
def open_file(filename):
with open(filename, 'rb') as f:
reader = unicodecsv.DictReader(f)
return list(reader)
enrollments = open_file(enrollments_filename)
# Takes a date as a string, and returns a Python datetime object.
# If there is no date given, returns None
from datetime import datetime as dt
def parse_date(date):
if date == '':
return None
else:
return dt.strptime(date, '%Y-%m-%d')
# Takes a string which is either an empty string or represents an integer,
# and returns an int or None.
def parse_maybe_int(i):
if i == '':
return None
else:
return int(i)
for enrollment in enrollments:
enrollment['cancel_date'] = parse_date(enrollment['cancel_date'])
enrollment['days_to_cancel'] = parse_maybe_int(enrollment['days_to_cancel'])
enrollment['is_canceled'] = enrollment['is_canceled'] == 'True'
enrollment['is_udacity'] = enrollment['is_udacity'] == 'True'
enrollment['join_date'] = parse_date(enrollment['join_date'])
enrollments[0]
这是我得到的错误:
TypeError: strptime() argument 1 must be string, not datetime.datetime
任何人都可以向我解释原因吗?当我将date
更改为str(date)
时,这是我得到的错误:
//anaconda/lib/python2.7/_strptime.pyc in _strptime(data_string, format)
333 if len(data_string) != found.end():
334 raise ValueError("unconverted data remains: %s" %
--> 335 data_string[found.end():])
336
337 year = None
ValueError: unconverted data remains: 00:00:00
奇怪的是,当我第一次运行代码时,它可以工作。但后来我第二次重新按下并返回错误!非常感谢!
答案 0 :(得分:0)
我打赌你在shell / session中两次运行这行:
enrollment['cancel_date'] = parse_date(enrollment['cancel_date'])
第一次有效,但现在注册[' cancel_date']是日期,而不是字符串。第二次运行它 - 错误。