python对时间戳排序
时间: 2023-11-14 20:07:41 浏览: 35
可以使用Python内置模块time来将时间戳转化为时间格式,并使用sorted函数进行排序。以下是示例代码:
```python
import time
timestamps = [1585321961, 1585321959, 1585321962]
dates = [time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ts)) for ts in timestamps]
sorted_dates = sorted(dates)
print(sorted_dates)
```
输出结果为:
```
['2020-03-27 09:52:39', '2020-03-27 09:52:41', '2020-03-27 09:52:42']
```
相关问题
python怎么对时间戳排序?
可以使用sorted函数,将时间戳作为key进行排序,示例代码如下:
timestamps = [156726720, 156735360, 156744000]
sorted_timestamps = sorted(timestamps, key=lambda x: x)
print(sorted_timestamps)
输出结果为:
[156726720, 156735360, 156744000]
数组 年月日时分秒转时间戳进行排序
可以先将数组中的年月日时分秒转换成时间戳,然后使用排序算法对时间戳进行排序,最后再将排序后的时间戳转换成日期时间格式。
以下是一个示例代码:
```python
import time
# 假设有一个数组存储了多个日期时间字符串
date_strs = ["2022-01-01 12:00:00", "2021-12-31 18:30:00", "2022-01-02 09:00:00"]
# 将日期时间字符串转换为时间戳并存储到新的数组中
timestamps = []
for date_str in date_strs:
timestamp = time.mktime(time.strptime(date_str, "%Y-%m-%d %H:%M:%S"))
timestamps.append(timestamp)
# 对时间戳进行排序
sorted_timestamps = sorted(timestamps)
# 将排序后的时间戳转换为日期时间字符串并打印出来
for timestamp in sorted_timestamps:
date_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
print(date_str)
```
输出结果为:
```
2021-12-31 18:30:00
2022-01-01 12:00:00
2022-01-02 09:00:00
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)