pythonpandasdatetimeto-date

how to read data from csv as date format in python pandas


I have data in following format

Month        Country BA Total
11/1/2018     CN     3   10 

after reading Month comes as object though I want in date format, I tried to convert it in date time format using

hs = pd.read_csv('history.csv',parse_dates=['Month'])  #this is not solving the issue either

hs['Month'] = pd.to_datetime(hs['Month']) #this throws error

Please suggest me how to read it as date or convert it to date format


Solution

  • Try this

    from datetime import datetime
    dateparse = lambda x: datetime.strptime(x, '%m/%d/%Y')
    
    df = pd.read_csv('history.csv', parse_dates=['Month'], date_parser=dateparse)