pythonlistdictionarydatetimeseconds

convert seconds in list of dictionaries into hours, python


I'm trying to convert the seconds in my list of dictionaries into hours using the DateTime package from python. Eg.g instead of 'Duration': 745200 (seconds) I want 'Duration': 207:00:00 (hours:minutes:seconds). Could someone help me with how to achieve this? Thank you!

id_duration = 
[{'Id': 44, 'Duration': 745200},
 {'Id': 45, 'Duration': 259200},
 {'Id': 58, 'Duration': 21600},
 {'Id': 61, 'Duration': 597600}]

Solution

  • First of all start by importing the package

    import datetime
    

    Then let's define a function for that, using datetime.timedelta

    def convert_duration(duration_list):
        for i in duration_list:
            i['Duration'] = datetime.timedelta(seconds=i['Duration'])
            i['Duration'] = i['Duration'].total_seconds()
            i['Duration'] = i['Duration'] / 3600
        return duration_list
    

    Now let's test using the example you give

    id_duration = [{'Id': 44, 'Duration': 745200}, {'Id': 45, 'Duration': 259200}, {'Id': 58, 'Duration': 21600}, {'Id': 61, 'Duration': 597600}]
    
    print(convert_duration(id_duration))
    
    [Out]: [{'Id': 44, 'Duration': 207.0}, {'Id': 45, 'Duration': 72.0}, {'Id': 58, 'Duration': 6.0}, {'Id': 61, 'Duration': 166.0}]