首页 > 解决方案 > 使用 Python 从一系列日期检查项目列表

问题描述

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

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']

标签: pythondatetime

解决方案


您可以使用该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

推荐阅读