1

A rather simple problem, that i can't seem to figure.

Setup

Given a datetime.date or pandas.datetime I am trying to offset some dates that inevitably will be converted via pandas.to_datetime into an object that fails when used with numpy.busday_offset, as shown in the example below.

import numpy as np
import pandas as pd
#Works fine
np.busday_offset(datetime.date(2020, 1, 1), 3)
# Fails
np.busday_offset(pd.to_datetime(datetime.date(2020, 1, 1)), 3)
# Fails
np.busday_offset(pd.to_datetime(datetime.date(2020, 1, 1)).to_numpy(), 3)
#Works fine
pd.bdate_range(start = datetime.date(2020, 1, 1), 
               end = datetime.date(2020, 4, 14), 
               freq = '20B')
# Fails
np.busday_offset(pd.bdate_range(start = datetime.date(2020, 1, 1), 
                                end = datetime.date(2020, 4, 14), 
                                freq = '20B'), 3)

Question

How does one go from a date on the format datetime64[ns] (created by pandas.to_datetime or pandas.bdate_date) to datetime64[D] (which is recognized by numpy.busday_offset?

2 Answers 2

1

The problem seems to be the data type generated by pd.to_datetime is not compatible with np.busday_offset. It needs to be converted to a date first.

np.busday_offset(pd.to_datetime(datetime.date(2020, 1, 1)).date(), 3)

Similarly for the date_range, you can do something like:

drange = pd.bdate_range(start = datetime.date(2020, 1, 1), end = datetime.date(2020, 4, 14),freq = '20B')
np.busday_offset([e.date() for e in drange], 3)
Sign up to request clarification or add additional context in comments.

Comments

1

In addition to Allens answer, I found another answer together with some colleagues

import numpy as np
import pandas as pd
#Works fine
np.busday_offset(datetime.date(2020, 1, 1), 3)
# works fine now
np.busday_offset(pd.to_datetime(datetime.date(2020, 1, 1)).to_numpy().astype('datetime64[D]'), 3)
# works fine now
np.busday_offset(pd.to_datetime(datetime.date(2020, 1, 1)).to_numpy().astype('datetime64[D]'), 3)
#Works fine
pd.bdate_range(start = datetime.date(2020, 1, 1), 
               end = datetime.date(2020, 4, 14), 
               freq = '20B')
# works fine now
np.busday_offset(pd.bdate_range(start = datetime.date(2020, 1, 1), 
                                end = datetime.date(2020, 4, 14), 
                                freq = '20B').to_numpy().astype('datetime64[D]'), 3)

Comments

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.