Importing dates from a CSV file is always a hassle. With myriads of DateTime formats possible, we will need to write extensive amounts of code to accommodate al possible DateTime formats or put restrictions on the contents of the CSV file. We don’t want to do either. Instead of hard-coding commands like
map(datetime.strftime(string, “%m/%d/%Y))
into our codes, we can use pandas to convert the dates for us. Pandas has the capability to convert an entire column of dates in string format to DateTime format. We just need to be careful when importing just dates and not DateTime objects(strings). Pandas usually converts to DateTime objects. If we are just importing dates then the time components are undesirable. We will need to strip off the time part using .date() at the end. So instead of
pd.to_datetime(date)
we will need to use
pd.to_datetime(date).date()
An example script illustrates this procedure.
def dateformat(self, date): # use pandas to convert a date to datetime format # extract just the date since pandas returns the date as Timestamp object # repack the date as datetime using datetime.datetime.combine() with time = 00:00 date = dt.datetime.combine(pd.to_datetime(date).date(), dt.datetime.min.time()) return date




