Search code examples
pythondatetimestrptimestrftime

In python..looking for a simple code to output string from datetime and float from a list


I would like to loop through each average(index[0]) and each hour(index[1]) (in this order) in the first five lists of: a = [[38.59, '15'], [23.81, '02'], [21.52, '20'], [16.8, '16'], [16.01, '21'], [14.74, '13'], [13.44, '10'], [13.24, '18'], [13.23, '14'], [11.46, '17']]

I would like to use the str.format() method to print the hour and average in the following format: output str = "15:00: 38.59 average comments per post"

To format the hours, I can use the datetime.strptime() constructor to return a datetime object and then use the strftime() method to specify the format of the time.

To format the average, I can use {:.2f} to indicate that just two decimal places should be used. How can I accomplish this with 2-3 lines of coding?


Solution

  • from datetime import datetime as dt
    
    a = [[38.59, '15'], [23.81, '02'], [21.52, '20'], [16.8, '16'], [16.01, '21'], [14.74, '13'], [13.44, '10'], [13.24, '18'], [13.23, '14'], [11.46, '17']]
    for elem in a[:5]:
        dtObj = dt.strptime(elem[1], '%H')
        timeString = dt.strftime(dtObj, '%H:%M')
        roundedAverageString = "{0:.2f}".format(elem[0])
        print("{}: {} average comments per post".format(timeString, roundedAverageString))
    

    output example: 15:00: 38.59 average comments per post