Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format timedelta for display

Tags:

python

My script calculate the difference in 2 time. Like this:

lasted = datetime.strptime(previous_time, FMT) - datetime.strptime(current_time, FMT)

It returns me a timedelta object. Currently, it gives me difference in seconds.

How can I format it for display nicely?

e.g. convert "121" to "00:02:01"?

Thank you.

like image 671
michael Avatar asked Nov 16 '12 02:11

michael


1 Answers

That fractional second bit is sometimes unwanted from a timedelta. A quick truncate of that fractional bit with a split and discard:

a = datetime.now()
b = datetime.now() - a

then

str(b).split('.')[0]

(assuming applications where fraction of a second is irrelevant to you)

like image 187
RossGK Avatar answered Sep 28 '22 20:09

RossGK