Search code examples
pythonpandasdate-range

Pandas _period_range function not working when extracted date from data frame


I need to access the date range from the data frame and specify in period_range() Issue: Even though I am passing a string as argument, it doesn't work. Kindly suggest where am I going wrong.

Dataframe

Below mentioning the code I tried:

import pandas as pd
import numpy as np
from datetime import datetime
datas=[['project1','26-06-2021','02-07-2021']]
cols=['project','startdate','enddate']
data1=pd.DataFrame(data=datas,columns=cols)
print(data1.head())
str1 =pd.to_datetime(data1['startdate'][0]).strftime('%Y-%m-%d')
str2 =pd.to_datetime(data1['enddate'][0]).strftime('%Y-%m-%d')
range=pd.period_range(str1,str2,freq='M')
print(range)

Result

PeriodIndex([], dtype='period[M]')


Solution

  • Problem is str1 is parsed like February, possible solution is add dayfirst=True parameter:

    str1 =pd.to_datetime(data1['startdate'][0], dayfirst=True).strftime('%Y-%m-%d')
    str2 =pd.to_datetime(data1['enddate'][0], dayfirst=True).strftime('%Y-%m-%d')
    r=pd.period_range(str1,str2,freq='M')
    print(r)
    PeriodIndex(['2021-06', '2021-07'], dtype='period[M]', freq='M')