5

I am trying to plot a duration in seconds with respect to some iteration values. I compute the duration values by substracting two datetime values. Then, I would like to plot these results in a very simple way using existing tools.

My code is the following but it doesn't work yet:

#!/usr/bin/env python

import datetime
import matplotlib.pyplot as plt
from numpy import arange

it = arange(10)
durations = [datetime.timedelta(hours=h+30) for h in it]

plt.plot(it, durations)

plt.show()

I got the following error:

TypeError: float() argument must be a string or a number

I know that I can make it work by using datetime instead of timedelta but my goal is to plot duration in hours (around 40 hours) so the rendering is not good.

1 Answer 1

7

That's because there is no defined conversion for timedelta to float. You can use:

durations = [datetime.timedelta(hours=h+30).total_seconds()/3600.0 for h in it]

to transform the duration to floating point hours. Look at how to format your tick labels if you want the nice hour notation on your plot. You can convert the hour (float) to a nicely formatted hour string.

(EDIT: changed .total_seconds to .total_seconds()

Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't it be timedelta.total_seconds(), else you'll just end up with the duration modulo one day?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.