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?

Community
  • 1
  • 1
Oliver
  • 8,169
  • 3
  • 15
  • 37

2 Answers2

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)
Allen Qin
  • 19,507
  • 8
  • 51
  • 67
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)
Oliver
  • 8,169
  • 3
  • 15
  • 37