Issue
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?
Solution
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')
Answered By - Tom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.