Pemi Ng Pemi Ng - 11 months ago 104
Python Question

Argument 1 must be string, not datetime.datetime?

I just took a Data Analysis course on Udacity.
My code is:

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
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
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'])


Here is the error I got:

TypeError: strptime() argument 1 must be string, not datetime.datetime

Can anyone explain to me why? When I change
, here is the error I got:

//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():])
337 year = None

ValueError: unconverted data remains: 00:00:00

The weird thing is, when I first ran the code, it works. But then I re-pressed the second time and it returned the error! Thanks very much!

Answer Source

I bet you ran this line twice in your shell/session:

enrollment['cancel_date'] = parse_date(enrollment['cancel_date'])

The first time works, but now enrollment['cancel_date'] is a date, not a string. Second time you ran it - error.