Working with Dates and Times in Python Lesson 10

Screen Link:

My Code:

appt_lengths = {}   
for row in potus:
    end_date = row[3]
    end_date = dt.datetime.strptime(end_date, "%m/%d/%y %H:%M")
    row[3] = end_date

    start_date = row[2]
    start_date = dt.datetime.strptime(start_date, "%m/%d/%y %H:%M")
    end_date = row[3]
    length = end_date - start_date
    if length not in appt_lengths:
        appt_lengths[length] = 1
    else:
        appt_lengths[length] += 1
        
min_length = min(appt_lengths)
max_length = max(appt_lengths)

What I expected to happen:

I expected not having an issue with parsing the start_date.

What actually happened:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-99063a7e1785> in <module>
      6 
      7     start_date = row[2]
----> 8     start_date = dt.datetime.strptime(start_date, "%m/%d/%y %H:%M")
      9     end_date = row[3]
     10     length = end_date - start_date

TypeError: strptime() argument 1 must be str, not datetime.datetime
  1. In the answer, how come I do not need to use the dt.datetime.strptime for start_date? If it is used for end_date why is it not needed for start_date?

  2. Is it possible for me to put the start_date portion in the same loop as the end_date or is a new for loop necessary for the start_date?

  3. In the answer, if end_date is being equaled to row[2] (in the bottom for loop - which is the element in potus dataset), why was the top for loop necessary?

1 Like

You will have to cross-check, but, I believe, the start_date were already converted in a previous screen in that lesson.

Depends on what you wish to do. But, a quick look at the instructions makes it seem it should be possible to do it in the same loop.

Could you clarify where it’s being equated to row[2]?

Hi, thank you for taking the time to respond!

  1. How can I cross-check this? I did a print(type(start_date)) and it shows <class ‘datetime.datetime’>, AND end_date is also the same even before I restart the code and comment out the provided for loop code.

  2. I will try to test this out.

  3. I think I understand third question. I was asking why was the top for loop necessary? But I see that the first for loop updated the potus dataset with the new end_date parsing. “end_date = row[3]” is needed to be type below for the second for loop so that it can be iterated over.

The answer so you can reference:
for row in potus:
end_date = row[3]
end_date = dt.datetime.strptime(end_date, “%m/%d/%y %H:%M”)
row[3] = end_date
appt_lengths = {}

for row in potus:
start_date = row[2]
end_date = row[3]
length = end_date - start_date
if length not in appt_lengths:
appt_lengths[length] = 1
else:
appt_lengths[length] += 1

min_length = min(appt_lengths)
max_length = max(appt_lengths)