假设我们有一个列表timestamps
包含多个时间戳,我们想要保留其中每个不同日期的第一个时间戳。以下是一个使用Python代码解决这个问题的示例:
timestamps = [
"2021-01-01 10:00:00",
"2021-01-01 11:00:00",
"2021-01-02 09:00:00",
"2021-01-02 10:00:00",
"2021-01-03 08:00:00",
"2021-01-03 09:00:00"
]
# 创建一个字典来存储每个日期的第一个时间戳
first_timestamps = {}
# 遍历时间戳列表
for timestamp in timestamps:
# 提取日期部分
date = timestamp.split(" ")[0]
# 如果日期不存在于字典中,则将当前时间戳添加到字典中
if date not in first_timestamps:
first_timestamps[date] = timestamp
# 输出结果
for timestamp in first_timestamps.values():
print(timestamp)
输出结果为:
2021-01-01 10:00:00
2021-01-02 09:00:00
2021-01-03 08:00:00
这个示例中,我们使用一个字典first_timestamps
来存储每个日期的第一个时间戳。我们遍历timestamps
列表,将日期部分提取出来,并检查该日期是否已存在于字典中。如果日期不存在,则将当前时间戳添加到字典中。最后,我们输出字典中的值,即每个日期的第一个时间戳。
下一篇:保留特定列中连字符后的字符串部分