pd.to_datetime is getting half my dates with flipped day / months

后端 未结 2 1997
梦谈多话
梦谈多话 2020-12-02 01:02

My dataset has dates in the European format, and I\'m struggling to convert it into the correct format before I pass it through a pd.to_datetime, so for all day < 12, my

相关标签:
2条回答
  • 2020-12-02 01:28

    Add format.

    df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y') 
    
    0 讨论(0)
  • 2020-12-02 01:40

    You can control the date construction directly if you define separate columns for 'year', 'month' and 'day', like this:

    import pandas as pd
    df = pd.DataFrame(
        {'Date': ['01/03/2018', '06/08/2018', '31/03/2018', '30/04/2018']}
    )
    date_parts = df['Date'].apply(lambda d: pd.Series(int(n) for n in d.split('/')))
    date_parts.columns = ['day', 'month', 'year']
    df['Date'] = pd.to_datetime(date_parts)
    
    date_parts
    #    day  month  year
    # 0    1      3  2018
    # 1    6      8  2018
    # 2   31      3  2018
    # 3   30      4  2018
    
    df
    #         Date
    # 0 2018-03-01
    # 1 2018-08-06
    # 2 2018-03-31
    # 3 2018-04-30
    
    0 讨论(0)
提交回复
热议问题