Format timedelta to string

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

    If you happen to have IPython in your packages (you should), it has (up to now, anyway) a very nice formatter for durations (in float seconds). That is used in various places, for example by the %%time cell magic. I like the format it produces for short durations:

    >>> from IPython.core.magics.execution import _format_time
    >>> 
    >>> for v in range(-9, 10, 2):
    ...     dt = 1.25 * 10**v
    ...     print(_format_time(dt))
    
    1.25 ns
    125 ns
    12.5 µs
    1.25 ms
    125 ms
    12.5 s
    20min 50s
    1d 10h 43min 20s
    144d 16h 13min 20s
    14467d 14h 13min 20s
    

提交回复
热议问题