Convert list to datetime in pandas

后端 未结 1 869

I have the foll. list in pandas:

str = jan_1 jan_15  feb_1   feb_15  mar_1   mar_15  apr_1   apr_15  may_1   may_15  jun_1   jun_15  jul_1   jul_15  aug_1            


        
1条回答
  •  独厮守ぢ
    2020-12-21 11:45

    You have to specify the format argument while calling pd.to_datetime. Try

    pd.to_datetime(pd.Series(s), format='%b_%d')
    

    this gives

    0   1900-01-01
    1   1900-01-15
    2   1900-02-01
    3   1900-02-15
    4   1900-03-01
    5   1900-03-15
    6   1900-04-01
    7   1900-04-15
    8   1900-05-01
    9   1900-05-15
    

    For setting the current year, a hack may be required, like

    pd.to_datetime(pd.Series(s) + '_2015', format='%b_%d_%Y')
    

    to get

    0   2015-01-01
    1   2015-01-15
    2   2015-02-01
    3   2015-02-15
    4   2015-03-01
    5   2015-03-15
    6   2015-04-01
    7   2015-04-15
    8   2015-05-01
    9   2015-05-15
    

    0 讨论(0)
提交回复
热议问题