Search code examples
pythonpandasdatetimestrptime

Parse dates for datetype as DDMMMYYYY


Currently my data has date as 01JAN2017, how do I make pandas understand this as date type, i need the data to be in date type for filtering it for various time frames. i used the below

data=pd.read_csv(input_path + 'data.txt',sep='|', parse_dates=['week'])

but when i checked for the datatype for week it still shows as object.

Would be very helpful if you can also direct me to some other links so that i could read up more about this


Solution

  • You can use datetime.strptime() to parse a date string into a datetime object:

    >>> from datetime import datetime
    >>> datetime.strptime("01JAN2017", "%d%b%Y")
    >>> datetime.datetime(2017, 1, 1, 0, 0)
    

    Now, to make pandas recognize the format, you could add a date parser function:

    dateparse = lambda dates: [pd.datetime.strptime(d, "%d%b%Y") for d in dates]
    df = pd.read_csv(infile, parse_dates=["week"], date_parser=dateparse)