Add a total_seconds() method to timedelta64?

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

Add a total_seconds() method to timedelta64?

Chris Barker - NOAA Federal
I just noticed that there is no obvious way to convert a timedelta64 to seconds (or some other easy unit) as a number.

The stdlib datetime.datetime has a .total_seconds() method for doing that. I think it's a handy thing to have.

Looking at StackOverflow (and others), I see people suggesting things like:

a_timedelta.astype(np.float) / 1e6

This seems a really bad idea, as it's assuming the timedelta is storing milliseconds.

The "proper" way to do it also suggested:

a_timedelta / np.timedelta64(1, 's')

This is, in fact, a much better way to do it, and allows you to specify other units if you like: "ms"., "us", etc.

There was semi-recently a discussion thread on python-ideas about adding other methods to datetime: (e.g.  .total_hours, .total_minutes). That was pretty much rejected (or petered out anyway), and some argued that dividing by a timedelta of the unit you want is the "right" way to do it anyway (some argued that .total_seconds() never should have been added.

Personally I understand the "correctness" of using united-division, but "practicality beats purity", and the discoverability of a method or two really makes it easier on folks.

That being said, of folks don't want to add .total_seconds and the like -- we should add a bit to the docs about this, suggesting using the division approach.



Christopher Barker, Ph.D.

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

[hidden email]

NumPy-Discussion mailing list
[hidden email]