Format timedelta to string

后端 未结 28 2160
春和景丽
春和景丽 2020-11-22 03:57

I\'m having trouble formatting a datetime.timedelta object.

Here\'s what I\'m trying to do: I have a list of objects and one of the members of the cl

28条回答
  •  眼角桃花
    2020-11-22 04:25

    As you know, you can get the total_seconds from a timedelta object by accessing the .seconds attribute.

    Python provides the builtin function divmod() which allows for:

    s = 13420
    hours, remainder = divmod(s, 3600)
    minutes, seconds = divmod(remainder, 60)
    print '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
    # result: 03:43:40
    

    or you can convert to hours and remainder by using a combination of modulo and subtraction:

    # arbitrary number of seconds
    s = 13420
    # hours
    hours = s // 3600 
    # remaining seconds
    s = s - (hours * 3600)
    # minutes
    minutes = s // 60
    # remaining seconds
    seconds = s - (minutes * 60)
    # total time
    print '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
    # result: 03:43:40
    

提交回复
热议问题