Format timedelta to string

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

    One liner. Since timedeltas do not offer datetime's strftime, bring the timedelta back to a datetime, and use stftime.

    This can not only achieve the OP's requested format Hours:Minutes, now you can leverage the full formatting power of datetime's strftime, should your requirements change to another representation.

    import datetime
    td = datetime.timedelta(hours=2, minutes=10, seconds=5)
    print(td)
    print(datetime.datetime.strftime(datetime.datetime.strptime(str(td), "%H:%M:%S"), "%H:%M"))
    
    Output:
    2:10:05
    02:10
    

    This also solves the annoyance that timedeltas are formatted into strings as H:MM:SS rather than HH:MM:SS, which lead me to this problem, and the solution I've shared.

提交回复
热议问题