如果您有两种不同的格式,如何将列更改为一种日期格式?

How to change a column into one date format if you have two different format?

所以,我有一个具有两种不同日期格式的日期列,例如:

1/2/2011

13-01-2011

我有代码:

superstore['Order Month'] = superstore['Order Date'].apply(lambda x: datetime.datetime.strptime(x, "%d/%m/%Y").strftime('%m/%Y'))

Google Colab return

ValueError: time data '13-01-2011' does not match format '%d/%m/%Y'

如何解决?

使用if 语句检查每个条目中的格式并应用正确的格式。例如:

def convert(x):
    date_format = "%d/%m/%Y" if '/' in x else "%d-%m-%Y"
    return datetime.datetime.strptime(x, date_format).strftime('%m/%Y')
    
superstore['Order Month'] = superstore['Order Date'].apply(convert)