Format timedelta to string

后端 未结 28 1703
春和景丽
春和景丽 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:24

    He already has a timedelta object so why not use its built-in method total_seconds() to convert it to seconds, then use divmod() to get hours and minutes?

    hours, remainder = divmod(myTimeDelta.total_seconds(), 3600)
    minutes, seconds = divmod(remainder, 60)
    
    # Formatted only for hours and minutes as requested
    print '%s:%s' % (hours, minutes)
    

    This works regardless if the time delta has even days or years.

提交回复
热议问题