python-3.xpandasnumpydatetime64

Converting pandas datetime to numpy datetime


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?


Solution

  • 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)