CYBER WEEK - EXTRA SAVINGS EVENT
TRY A FREE LESSON

Hacker News Project, Question about purpose of Instruction on Screen 7

Screen Link: https://app.dataquest.io/c/62/m/356/guided-project%3A-exploring-hacker-news-posts/7/sorting-and-printing-values-from-a-list-of-lists

This is not a question about my code functionality, but about the purpose of a certain instruction. Here are the instructions I’m wondering about:

  1. Use the str.format() method to print the hour and average in the following format: 15:00: 38.59 average comments per post.
  • To format the hours, use the datetime.strptime() constructor to return a datetime object, and then use the strftime() method to specify the format of the time.

Currently the hour is stored as a two character string. We are not adding specific minutes, just 00. So why convert the string to a datetime object, and then reformat back to a string?

Why not just create a string like so: new_hour_string = hour_string + ':00' ?
Is there a purpose to what is suggested in the instructions?

ETA: I’ve tried it both ways and got the same exact results.
Here is my code written both ways:

#display top 5 hours for comments
print("Top 5 Hours for Ask Posts Comments: ", '\n')
template = "{}: {:.2f} average comments per post"
for row in sorted_swap[:5]:
    hour = row[1] + ':00'
    comments = row[0]
    print(template.format(hour, comments))
    
print('\n')
#display top 5 hours for comments
print("Top 5 Hours for Ask Posts Comments: ", '\n')
template = "{}: {:.2f} average comments per post"
for row in sorted_swap[:5]:
    hour_dt = dt.datetime.strptime(row[1], "%H")
    hour = hour_dt.strftime("%H:%M")
    comments = row[0]
    print(template.format(hour, comments))

And here are the results of both code blocks (same both ways!):

Top 5 Hours for Ask Posts Comments:

15:00: 38.59 average comments per post
02:00: 23.81 average comments per post
20:00: 21.52 average comments per post
16:00: 16.80 average comments per post
21:00: 16.01 average comments per post

Top 5 Hours for Ask Posts Comments:

15:00: 38.59 average comments per post
02:00: 23.81 average comments per post
20:00: 21.52 average comments per post
16:00: 16.80 average comments per post
21:00: 16.01 average comments per post