如何对时间列表进行排序

2024-05-02 16:52:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始使用Python,想知道如何对其进行排序

从最早到最晚列出。在

('5:00PM','2:00PM','7:00AM','8:45PM','12:00PM')

感谢任何帮助。在


Tags: 排序
3条回答

我建议您安装PyPi DateTime包,并将这些工具用于您想要的任何操作。眼前的问题看起来像:

stamps = ('5:00PM','2:00PM','7:00AM','8:45PM','12:00PM')
DT_stamps = [DateTime(s) for s in stamps]
DT_stamps.sort()

实施细节留作学生练习。:-)

仅在带标准库的python3中:

import time
hours = ('5:00PM','2:00PM','7:00AM','8:45PM','12:00PM')
format = '%I:%M%p'
time_hours = [time.strptime(t, format) for t in hours]
result = [time.strftime(format, h) for h in sorted(time_hours)]
assert result == ['07:00AM', '12:00PM', '02:00PM', '05:00PM', '08:45PM']

如果《纽约时报》总是采用这种格式,那么您可以将《纽约时报》分成若干小节。在

x = "12:30PM"
# Use python's string slicing to split on the last two characters
time, day_half = x[:-2], x[-2:]
# Use python's string.split() function to get the difference between hours and minutes
# Because "11" < "2" for strings, we need to convert them to integers
hour, minute = [int(t) for t in time.split(":")]
# Get the remainder because 12 should actually be 0
hour = hour % 12
# Output it as a tuple, which sorts based on each element from left to right
sortable = (day_half, hour, minute)
#: ("PM", 12, 30)

总而言之,请使用类似以下内容:

^{pr2}$

如果不能保证两个字母在末尾,或者冒号在中间,那么最好使用Prune建议的库。在

相关问题 更多 >