在 Python 中将时间戳从字符串“字母”排序为数字

问题描述 投票:0回答:1

我有从第三方应用程序收到的数据,其中一列是时间戳,我得到 48 个时间戳值。 问题是我按字母顺序获取时间戳,因此数字 10 出现在数字 9 之上,因为它按字母顺序排序,比较第一个数字。 我需要一种方法来正确地重新排列时间戳,例如将数字转换为两位数并比较数字,以便根据数字对它们进行正确排序。 检查以下附图“SampleData1”和“SampleData2”,突出显示的蓝色是我接收订购数据的方式,突出显示的绿色是我需要组织数据的方式。 样本数据1 样本数据2

我需要将日期转换为 MM/DD/YYYY 并对 AM 和 PM 进行排序

python timestamp
1个回答
0
投票

这是用于按给定格式对日期字符串列表进行排序的 Python 代码。

from datetime import datetime

# List of date strings
example_strings = [
    "5/10/24 12:00:03 AM",
    "5/11/24 12:00:34 PM",
    "5/9/24 09:30:00 AM",
    "5/11/24 06:15:22 AM"
]

# Define the format of the date string
date_format = "%m/%d/%y %I:%M:%S %p"

# Convert the strings to datetime objects
timestamps = [datetime.strptime(date_str, date_format) for date_str in example_strings]

# Sort the list of datetime objects
sorted_timestamps = sorted(timestamps)

# Convert sorted datetime objects back to strings
sorted_date_strings = [timestamp.strftime(date_format) for timestamp in sorted_timestamps]

# Print sorted date strings:
for date_str in sorted_date_strings:
    print(date_str)

输出:

05/09/24 09:30:00 AM
05/10/24 12:00:03 AM
05/11/24 06:15:22 AM
05/11/24 12:00:34 PM
© www.soinside.com 2019 - 2024. All rights reserved.