python - 使用 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']
解决方案
您可以使用该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
推荐阅读
- closures - 组成换能器;组成顺序和执行顺序
- php - 访问 Laravel 7 中的子属性
- python - 有没有比这种方法更有效的方法?
- python - Python:熊猫中的行到列转换
- machine-learning - PyTorch 中每个时期的准确度
- android - Android Studio Flutter 项目无法识别 build.gradle 中的 GradleException 和 Properties
- multithreading - 后台线程和任务
- android - Retrofit 2 在 POST 查询中返回 GET 响应
- python - Python散景随机颜色生成器
- c++ - C ++:使用future.get超时且不阻塞