changing format of time duration.

D

dave

Quick question. I have to time stamps (now and now2).

now = datetime.datetime.now();
now2 = datetime.datetime.now();

now2-now1 yields me a result in 0:00:00.11221 (H:MM:SS.ssss)

I wanted to know if there is a standard python method or a quick hack
to add an extra zero in the beginning.

So the result I am looking for would be 00:00:00.11221
 
G

Gabriel Genellina

Quick question. I have to time stamps (now and now2).

now = datetime.datetime.now();
now2 = datetime.datetime.now();

now2-now1 yields me a result in 0:00:00.11221 (H:MM:SS.ssss)

I wanted to know if there is a standard python method or a quick hack
to add an extra zero in the beginning.

So the result I am looking for would be 00:00:00.11221

Try the strptime method with a suitable format, like this (untested):
delta = now2-now1
delta.strftime('%H:%M:%S.%f')

http://docs.python.org/library/datetime.html#strftime-strptime-behavior
 
G

Günther Dietrich

Gabriel Genellina said:
Try the strptime method with a suitable format, like this (untested):
delta = now2-now1
delta.strftime('%H:%M:%S.%f')

Throws an exception:

|Traceback (most recent call last):
| File "<stdin>", line 1, in <module>
|AttributeError: 'datetime.timedelta' object has no attribute 'strftime'

What seems logical, since the documentation doesn't mention an strftime
method for timedelta.



Regards,

Günther
 
G

Gabriel Genellina

Throws an exception:

|Traceback (most recent call last):
|  File "<stdin>", line 1, in <module>
|AttributeError: 'datetime.timedelta' object has no attribute 'strftime'

What seems logical, since the documentation doesn't mention an strftime
method for timedelta.

You're right. Second try (still untested):

def nice_timedelta_str(d):
result = str(d)
if result[1] == ':':
result = '0' + result
return result

delta = now2-now1
print nice_timedelta_str(delta)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top