Guided Project: Exploring Hacker News Posts 7/8 Time Zone Conversion

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

This is the code I have for the original time zone below in EST

print("Top 5 Hours for Ask Posts Comments")
date_format = "%H"

for i in sorted_swap[:5]:
    avg = "{:.2f}".format(i[0]) #two decimal places should be used 
    hours = i[1]
    hour = dt.datetime.strptime(hours, date_format) #format the hours by using the datetime.strptime() constructor to return a datetime object
    time = hour.strftime("%H") #using the strftime() method to specify the format of the time
    print("{time}:00 : {value} average comments per post".format(time=hours, value=avg) ) 
  

In the next cell, I wanted to convert the EST timezone to GMT + 1, which is essentially plus 7 hours. This is the code I used for the conversion below:

# The original time zone was Eastern Standard.
# Here I am converting to GMT+1 by adding 7 hours.

print("Top 5 Hours for Ask Posts Comments in GMT+1")
date_format = "%H"

for i in sorted_swap[:5]:
    avg = "{:.2f}".format(i[0]) #two decimal places should be used 
    hours = i[1]
    hour = dt.datetime.strptime(hours, date_format)
    hour_in_gmt = hour + dt.timedelta(hours=7)
    time = hour_in_gmt.strftime("%H")
    print("{time}:00 : {value} average comments per post".format(time=hours, value=avg)) 
  

However, I find my output is exactly the same in both codes, i.e. the hours remained unchanged. Please can someone help me figure out why, or how to successfully convert the time zone. The output I’m getting for both codes is below

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

Thank you

Hello @kay.k,

The code you used for the conversion is correct.

However, while using the string.format() method to print out the result of the conversion, the value of the time placeholder is not correct .

Kindly note that from your second code block, this line of code: time = hour_in_gmt.strftime("%H"), assigns the string output to the varibale time.

Hence, the last line of code in the code block used for conversion should be:
print("{time}:00 : {value} average comments per post".format(time=time, value=avg)).

I hope this helps.

1 Like

Many many thanks @doyinsolamiolaoye for helping to spot that!

Now getting the right output - appreciated! :slight_smile:

1 Like

@kay.k

I’m happy I could be of help. I would appreciate it if you could mark the reply as a solution. Thank you. :blush: