Questions about "strftime" & "strptime"

In this project, the 2 menthods appear twice:

  1. when creating the hour of day:
for each_row in result_list:
    date = each_row[0]
    comment = each_row[1]
    time = dt.datetime.strptime(date, date_format).strftime("%H")
  1. When printing the Top 5 hours:
print("Top 5 Hours for 'Ask HN' Comments")
for avg, hr in sorted_swap[:5]:
    print(
        "{}: {:.2f} average comments per post".format(
            dt.datetime.strptime(hr, "%H").strftime("%H:%M"),avg
        )
    )

In the previous mission, the 2 methods are not used together. So I’m really confused by the usage of them in this project. Here are 3 of my questions:

  1. can the 2 menthods used in different lines? what will it looks like if they’re not in the same line?
  2. in the first code why use “strftime("%H")”?i thought it is to format the datetime. How does it transfer a long datetime into just an hour?
  3. in the 2nd code, why can’t we just use"strftime" alone?

Hello, Ling! I hope I can help you:

First off, strptime and strftime serve different purposes.

  • striptime: it is class method that creates a datetime object from a string representing a date and time and a corresponding format string. datetime.datetime.strptime(date_string, format_of_the_datetime_in_my_date_string)
  • strftime: it is used for presenting the datetime object under certain format (it is a class attribute). It creates a string representing the time under the control of an explicit format string. datetime.striftime(format_I_want_to_show_my_date_time_object)

So:

  1. I can use strptime alone, with no strftime. But I can only use strftime over an datetime object (which I can create using strptime).
  2. As strftime is just for formatting, it kinda “maps” the datetime knowing what is representing hours, minutes, years, days, and so on. So when I write `datetime.strftime("%H"), it means that I want to show only the hours of my datetime object.
  3. Because you need to declare which format you want the datetime to appear.
my_date_time_object = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
#Now I want to show only the month and year of my datetime
print(my_date_time_object.strftime('%m/%Y'))
> 11/2006 #this is the result

I hope it helped :blush:

1 Like

Hi @marianafmedeiros, thank you so much for the reply and and answers! It makes sense to me.

1 Like