0

From a pandas DataFrame, when I extract the value of a specific timedelta field, I receive an object of type numpy.timedelta64:

>>> numpy_delta
numpy.timedelta64(-2700000000000,'ns')

I understand that this is numpy's representation for "-2700000000000 Nanoseconds". How can I create an object datetime.timedelta from that numpy object to use it outside of numpy?
From my expectations, that solution should provide:

>>> datetime_timedelta
datetime.timedelta(days=-1, seconds=83700)
Judge
  • 644
  • 8
  • 11

1 Answers1

0

When working with datetime64 dtype arrays, tolist() or item() do a good job of converting the array to base Python objects. Let's try that with your timedelta:

In [174]: x=np.timedelta64(-2700000000000,'ns')
In [175]: x.item()
Out[175]: -2700000000000

Not quite what we want. But if I first convert it to minutes:

In [176]: x.astype('timedelta64[m]')
Out[176]: numpy.timedelta64(-45,'m')
In [177]: x.astype('timedelta64[m]').item()
Out[177]: datetime.timedelta(days=-1, seconds=83700)
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Hey @hpaulj, thanks for your contribution! From the demo code you shared, that 'hack' obviously works, but having the solution right before my eyes, I still do not get it: Why does `x.item()` return a `int`, while a `numpy.timedelta64`, that got converted to "minutes", returns a `datetime.timedelta`? – Judge Nov 01 '20 at 19:03
  • I haven't studied the relevant `c` code – hpaulj Nov 01 '20 at 19:21
  • I do not mean how the backend code performs these conversions - I mean: I'd like to get the logic behind that. How would I come to an idea like that next time without StackOverflow? ;) Did you find this in any Doc? Or: Where do YOU know it works like this from? – Judge Nov 01 '20 at 19:43
  • I just experimented. I knew from past use that the `datetime64` dtype produced `datetime` lists, so expected the `timedelta` to behave similarly. I don't know why the smallest units unpacks to an integer. The implementation of datetimes in `numpy` is relatively new and in need of improvement. `matplotlib` has been handling dates for some time. `pandas` may also be more consistent. – hpaulj Nov 01 '20 at 20:13