When do you place the name of the class before a method?

Code exercise 1:

import datetime as dt
date_format = "%m/%d/%y %H:%M"

for abc in potus:
    start_date = abc[2]
    start_date = dt.datetime.strptime(start_date, date_format)
    abc[2] = start_date

link to exercise: https://app.dataquest.io/m/353/working-with-dates-and-times-in-python/5/using-strptime-to-parse-strings-as-dates

Code exercise 2:

for row in potus:
    month_dt = row[2]
    month_str = month_dt.strftime("%B, %Y")
    if month_str not in visitors_per_month:
        visitors_per_month[month_str] = 1
    else:
        visitors_per_month[month_str] += 1

link to exercise: https://app.dataquest.io/m/353/working-with-dates-and-times-in-python/6/using-strftime-to-format-dates

Question:
In the first exercise, i have to put the class name: .dt in front of the methode: .strptime for the object start_date . In the second exercise, this doesn’t have to be done for the object: month_str when i use the methode: strftime. My question: Why and when do you put the class name in front of the methode and when it is not necessary

2 Likes

In the first exercise the type of start_date is string that is why we had to call strptime explicitly.
You can check type using print(type(start_date)) in the for loop.


While in second exercise the type of month_dt is datetime.datetime so we can call directly strftime as it is type of same class.

You can check type using print(type(month_dt)) in the for loop.

1 Like

@joroenstikkelorum I had the same question too. @DishinGoyani 's response is correct. One thing to add, I believe that I think ‘month_dt’ has been converted in to the ‘datetime.datetime’ class in the exercise for you. If ‘month_dt’ had not been converted already in exercise 2 then you would have needed to call the ‘dt.datetime’ class.

Can someone please correct me if this is wrong?

1 Like

Yes that is right. @haddon.r.alexander