Search code examples
pythonpython-datetimetimedelta

Python list and datetime module


I have this list in Python:

youtube_time = ['23:15:02', '23:03:19', '18:52:23',
                '20:26:46', '57:41:07', '51:45:11',
                '47:20:26', '43:24:26', '127:41:49']

Each item in this list is the length of the video in the format: hours, minutes, seconds. How can I add up all the items in the list to get this result: 17 days, 5:30:29

You need to use the datetime module

I`m begginer in Python, and i dont know how


Solution

  • Just use the timedelta from datetime:

    from datetime import timedelta
    
    youtube_time = ['23:15:02', '23:03:19', '18:52:23', '20:26:46', '57:41:07', '51:45:11', '47:20:26', '43:24:26', '127:41:49']
    
    
    def get_total_time_delta(time_list: list) -> timedelta:
        total_time = timedelta()
        for time in time_list:
            hours, minutes, seconds = [int(i) for i in time.split(':')]
            total_time += timedelta(hours=hours, minutes=minutes, seconds=seconds)
        return total_time
    
    result = get_total_time_delta(youtube_time)
    
    print(result)