user12770072
user12770072

Reputation:

How to add fractional days using timedelta64?

t0 = np.datetime64(datetime(2000, 1, 1, 0, 0, 0))
t0 + np.timedelta64(1, 'D')

This is the output:

numpy.datetime64('2000-01-02T00:00:00.000000')

I want to add fractional days:

t0 + np.timedelta64(1.379, 'D')

Above command gives the error

ValueError: Could not convert object to NumPy timedelta

Is there a simple way to add fractional days?

Upvotes: 2

Views: 865

Answers (2)

phispi
phispi

Reputation: 869

Additionally to making use of datetime.timedelta or pandas.Timestamp as mentioned in the accepted answer you can also add precision with .astype:

t0 + 1.379 * np.timedelta64(1, 'D').astype('timedelta64[s]')

Upvotes: 0

Tom
Tom

Reputation: 8800

See this issue; numpy timedeltas have an internal integer representation, and they expect you to pick appropriate units to have integer values. But the standard datetime module can do this:

>>> import datetime as dt
>>> datetime(2000,1,1,0,0,0) + dt.timedelta(days=1.379)
datetime.datetime(2000, 1, 2, 9, 5, 45, 600000)

pandas also has a Timedelta that supports this:

>>> import pandas as pd
>>> datetime.datetime(2000, 1, 2, 9, 5, 45, 600000)
datetime.datetime(2000, 1, 2, 9, 5, 45, 600000)

# or using the pandas.Timestamp
>>> pd.Timestamp('01-01-2000') + pd.Timedelta(1.379, 'D')
Timestamp('2000-01-02 09:05:45.600000')

You can convert any of these back to numpy datetime if you want:

>>> np.datetime64(pd.Timestamp('01-01-2000'))
numpy.datetime64('2000-01-01T00:00:00.000000')

>>> np.datetime64(datetime(2000,1,1,0,0,0))
numpy.datetime64('2000-01-01T00:00:00.000000')

Otherwise,you need to convert your timedelta to new units (getting as precise as you want to be; in this case, milliseconds gives you the same answer):

>>> days = 1.379
>>> milliseconds = days * (24 * 60 * 60 * 1000)
>>> np.datetime64(datetime(2000,1,1,0,0,0)) + np.timedelta64(int(milliseconds), 'ms')
numpy.datetime64('2000-01-02T09:05:45.600000')

Upvotes: 3

Related Questions