Guided Project: Exploring Hacker News Posts step 7 of 8

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

I got to the final step, and had no clue as to how to “convert the times to the time zone you live in.”

hour_format = "%H"
for row in sorted_swap[:5]:
    hour = row[1]
    hour = dt.datetime.strptime(hour, hour_format)
    hour = hour.strftime("%H:%M")
    avg_comments = round(row[0],2)
    
    print("{0} {1} average comments per post".format(hour, avg_comments))

I’m sure I’m missing something obvious, but I’m drawing a blank.
FWIW, the times in the data set were Eastern Standard Time. I’m Central Standard Time, so I would need to subtract one hour.

Hey, Eroggenburg.

>>> import datetime as dt
>>> some_hour = "09"

Here are two different (and incomplete) ways to do it.

My prefered way

>>> dt.datetime.strptime(some_hour, "%H")
datetime.datetime(1900, 1, 1, 9, 0)
>>> dt.datetime.strptime(some_hour, "%H")+dt.timedelta(hours=1)
datetime.datetime(1900, 1, 1, 10, 0)

An alternative

>>> def add_one(s):
...     plus_one = int(s)+1
...     mod_24 = plus_one %24
...     return str(mod_24).zfill(2)
... 
>>> add_one(some_hour)
'10'

I realize I added instead of subtracting. I’ll let you make the necessary changes.

1 Like

Thank you, Bruno! I fiddled around and ended up with a much less elegant solution:

print("Top 5 Hours for Ask Posts Comments:")
hour_format = "%H"
for row in sorted_swap[:5]:
    hour = row[1]
    
    # The original time zone was Eastern Standard.
    # Here I am converting to Central Standard by subtracting an hour.
    convert_to_cst = dt.datetime.strptime(hour, hour_format)
    cst = convert_to_cst - dt.timedelta(hours=1)
    cst = cst.strftime("%H:%M")     
   
    avg_comments = round(row[0],2)
    print("{0} {1} average comments per post".format(cst, avg_comments))
1 Like

This is exactly what I mentioned above as it being my preferred way :slight_smile:

I just didn’t include all the details, just the necessary idea.

A post was split to a new topic: Why use datetime?

A post was split to a new topic: Unexpected EOF while parsing