pynovice
pynovice

Reputation: 7752

How to change timedelta into time duration in Python?

I have a timedelta time like this:

datetime.timedelta(0, 175, 941041)

I want to convert this into duration. For example:

1 second 
2-59 seconds
1 minute
2minutes-59minutes
1 hour
1 hour 50 minutes
2 hours
1 day 5 hours 45 minutes

How can I do this in Python?

First, I tried to converting timedelta into seconds like this and later convert into duration:

def timedelta_to_seconds(td):
    return td.microseconds + (td.seconds + td.days * 86400) 

But I get this error while running this function:

AttributeError: 'function' object has no attribute 'microseconds'

Upvotes: 0

Views: 1346

Answers (2)

AMADANON Inc.
AMADANON Inc.

Reputation: 5919

Ithink what you are passing to this function is not a timedelta, and that's why it has no attribute microseconds.

I have this from time to time, when I call a function to get the timedelta as

a=get_my_timedelta

instead of

a=get_my_timedelta()

Upvotes: 1

karthikr
karthikr

Reputation: 99630

You can just do

>>> import datetime
>>> str(datetime.timedelta(0, 175, 941041))
'0:02:55.941041'

Now you can get the Hours, minutes, seconds and milliseconds.

OR

Refer to this post if you want nice readable timedelta

Upvotes: 1

Related Questions