How to get total hours and minutes for timedelta in Python

后端 未结 3 579
孤街浪徒
孤街浪徒 2020-12-10 01:07

How do I return or turn a timedelta, which is bigger than 24 hours, into an object containing the total hours and minutes (for example, 26:30) instead of \"1 day, 2:30\"?

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 01:47

    offset_seconds = timedelta.total_seconds()
    
    if offset_seconds < 0:
        sign = "-"
    else:
        sign = "+"
    
    # we will prepend the sign while formatting
    if offset_seconds < 0:
        offset_seconds *= -1
    
    offset_hours = offset_seconds / 3600.0
    offset_minutes = (offset_hours % 1) * 60
    
    offset = "{:02d}:{:02d}".format(int(offset_hours), int(offset_minutes))
    offset = sign + offset
    

提交回复
热议问题