How to sort by timestamps in pandas?

前端 未结 1 1342
感动是毒
感动是毒 2020-12-20 14:57

So, I have timestamps that look like the following:

20140804:10:00:13.281486

20140804:10:00:13.400113

20140804:10:00:13.555512

20140804:10:00:13.435677


        
相关标签:
1条回答
  • 2020-12-20 15:13

    You just have to ensure you denote the format specification properly, and you can use pd.to_datetime to convert them to actual datetimes before sort_values.

    pd.to_datetime(stamps, format="%Y%m%d:%H:%M:%S.%f").sort_values()
    

    This is much more direct than decomposing the timestamps in components and performing a multiple-criteria sort as you were attempting.

    Demo

    >>> stamps
    0    20140804:10:00:13.281486
    1    20140804:10:00:13.400113
    2    20140804:10:00:13.555512
    3    20140804:10:00:13.435677
    dtype: object
    
    >>> pd.to_datetime(stamps, format="%Y%m%d:%H:%M:%S.%f").sort_values()
    0   2014-08-04 10:00:13.281486
    1   2014-08-04 10:00:13.400113
    3   2014-08-04 10:00:13.435677
    2   2014-08-04 10:00:13.555512
    dtype: datetime64[ns]
    
    0 讨论(0)
提交回复
热议问题