检查日期是否在接下来的10天内python

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

我的代码有问题。我有一个包含日期的列表,我希望此列表中接下来 10 天内的每个日期都附加到另一个列表中。但我的代码没有像我预期的那样工作。

代码:

    """
    Logic to sort into dates in the next 10 days
    -> Creates timedelta with 10 days, future date
    -> Checksif there is an date in the next days, which is a public holiday
    """
    list_upcoming_raw = []
    ten_days = timedelta(days=10)
    future_date = datetime.datetime.now() + ten_days

    for i in data_list:
        date = datetime.datetime.strptime(i, '%y%m%d')
        if date <= future_date:
            list_upcoming_raw.append(date.date())
    list_upcoming_raw.sort()

列表中的内容示例:

240223
240328
240329
240401
240402
240403
240404
240405
240501
240508
240509
240510
240520
240521
240620
240621
240624
240625
240626

感谢您的帮助!

python date datetime time
1个回答
1
投票

这是更正后的代码:

import datetime

# Example list of dates in string format
data_list = [
    '240223', '240328', '240329', '240401', '240402', '240403',
    '240404', '240405', '240501', '240508', '240509', '240510',
    '240520', '240521', '240620', '240621', '240624', '240625', '240626'
]

# Initial setup
list_upcoming_raw = []
ten_days = datetime.timedelta(days=10)
future_date = datetime.datetime.now() + ten_days

# Process each date in the data list
for i in data_list:
    date = datetime.datetime.strptime(i, '%y%m%d')
    
    # Check if the date is within the next 10 days
    if date <= future_date:
        list_upcoming_raw.append(date.date())

list_upcoming_raw.sort()

for d in list_upcoming_raw:
    print(d)
© www.soinside.com 2019 - 2024. All rights reserved.