'create lambda for pandas read_excel

In PyCharm, I'm trying to create a date parser lambda to pass in to pandas.read_excel but it throws a TypeError: strptime() argument 1 must be string, not datetime.datetime:

parser = lambda x: datetime.strptime(x, "%d-%m-%y")
read_file = pd.read_excel(
    file_path, skiprows=2, parse_dates=[10, 13], date_parser=parser
)

Is there a better way to do this?



Solution 1:[1]

It could be that parse_dates and date_parser, which is optional, are conflicting.

One workaround is to use converters instead, as per Pandas read_excel documentation, like this:

from datetime import datetime

import pandas as pd

parser = lambda x: datetime.strptime(x, "%d-%m-%y")

df = pd.read_excel("path_to_file", skiprows=2, converters={10: parser, 13: parser})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Laurent