Skip to content Skip to sidebar Skip to footer

How To Sort By Timestamps In Pandas?

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 I have them in a DataFra

Solution 1:

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
020140804:10:00:13.281486120140804:10:00:13.400113220140804:10:00:13.555512320140804:10:00:13.435677
dtype: object

>>> pd.to_datetime(stamps, format="%Y%m%d:%H:%M:%S.%f").sort_values()
02014-08-0410:00:13.28148612014-08-0410:00:13.40011332014-08-0410:00:13.43567722014-08-0410:00:13.555512
dtype: datetime64[ns]

Post a Comment for "How To Sort By Timestamps In Pandas?"