datetime struggle with a pandas dataframe

I am running the following code:

filled_df = (ts.set_index(date_col)
                 .groupby(grouping)
                 .apply(lambda d: d.reindex(
                     pd.date_range(
                         mf_heuristic(d.index, champion_end), pd.to_datetime(
                             dt.datetime.now()
                         ),
                         freq='MS')
                 )
    )
        .drop(grouping, axis=1)
        .reset_index(grouping)
        .fillna(0)

with the predefinitions:

date_col = 'timepoint'
grouping = ['Level', 'Kontogruppe']
champion_end = fc_date - pd.DateOffset(months=13)

print(champion_end)
2021-03-01 00:00:00

print(ts)
Kontogruppe  Level   timepoint    data_value
0       A   ZBFO  2020-03-01      1
1       B   ZBFO  2020-07-01      1612.59
2       A   ZBFO  2020-08-01      1046.1

print(ts.dtypes)
Kontogruppe     object
Level           object
timepoint       object
data_value         float64
dtype: object
def mf_heuristic(date, champion_end):
        
        if min(date) < champion_end:
            start_date = min(date)
        else:
            
            start_date = min(date)
        return start_date

When I run the code, I get the following error massage:

TypeError: Cannot compare Timestamp with datetime.date. Use ts ==
pd.Timestamp(date) or ts.date() == date instead.

for the line with the mf_heuristic function.

If I try to put before:

ts[date_col] = pd.Timestamp(ts[date_col]) 

I get the error massage:

TypeError: function missing required argument ‘year’ (pos 1)

>Solution :

Try using to_datetime:

ts[date_col] = pd.to_datetime(ts[date_col])

Leave a Reply