Specifying date format when converting with pandas.to_datetime

前端 未结 2 1480
南方客
南方客 2020-12-01 15:48

I have data in a csv file with dates stored as strings in a standard UK format - %d/%m/%Y - meaning they look like:

12/01/2012
30/01/2012
         


        
2条回答
  •  情话喂你
    2020-12-01 16:45

    I think you are calling it correctly, and I posted this as an issue on github.

    You can just specify the format to to_datetime directly, for example:

    In [1]: s = pd.Series(['12/1/2012', '30/01/2012'])
    
    In [2]: pd.to_datetime(s, format='%d/%m/%Y')
    Out[2]:
    0   2012-01-12 00:00:00
    1   2012-01-30 00:00:00
    dtype: datetime64[ns]
    

    Update: As OP correctly points out this doesn't work with NaN, if you are happy with dayfirst=True (which works with NaN too):

    s.apply(pd.to_datetime, dayfirst=True)
    

    Worth noting that have to be careful using dayfirst (which is easier than specifying the exact format), since dayfirst isn't strict.

提交回复
热议问题