gpt4 book ai didi

python - 使用 Python 检查一系列日期的项目列表

转载 作者:太空宇宙 更新时间:2023-11-03 14:42:50 25 4
gpt4 key购买 nike

我需要打印 c 中 a 到 b 范围内的所有项目

01/08/2017, 02/08/2017, 03/08/2017, 04/08/2017, 05/08/2017, 06/08/2017, 07/08/2017, 08/08/2017, 09/08/2017, 10/08/2017, 11/08/2017, 12/08/2017, 13/08/2017, 14/08/2017, 15/08/2017, 16/08/2017, 17/08/2017, 18/08/2017, 19/08/2017, 20/08/2017, 21/08/2017, 22/08/2017, 23/08/2017, 24/08/2017, 25/08/2017, 26/08/2017, 27/08/2017, 28/08/2017

a = '01/08/2017'
b = '28/08/2017'
c = ['01/08/2017', '20/08/2017', '21/08/2017', '22/08/2017', '23/08/2017', '24/08/2017', '25/08/2020', '26/08/2020', '27/08/2020', '28/08/2020']

我的答案应该是:

['01/08/2017', '20/08/2017', '21/08/2017', '22/08/2017', '23/08/2017', '24/08/2017']

最佳答案

您可以使用datetime 模块:

import datetime
def to_datetime(d):
day, month, year = map(int, d.split('/'))
return datetime.datetime(year, month, day, 0, 0, 0)

a = '01/08/2017'
b = '28/08/2017'
_a = to_datetime(a)
_b = to_datetime(b)
c = ['01/08/2017', '20/08/2017', '21/08/2017', '22/08/2017', '23/08/2017', '24/08/2017', '25/08/2017', '26/08/2017', '27/08/2017', '28/08/2017']
for i in c:
if _a <= to_datetime(i) <= _b:
print(i)

输出:

01/08/2017
20/08/2017
21/08/2017
22/08/2017
23/08/2017
24/08/2017
25/08/2017
26/08/2017
27/08/2017
28/08/2017

关于python - 使用 Python 检查一系列日期的项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52081174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com