简体   繁体   English

循环遍历一系列日期以进行比较

[英]Looping through a range of dates for comparison

I have a list that records expenditures in this manner:我有一个以这种方式记录支出的清单:

expenditures = [
    (date(2019, 11, 16), 100, 'Transport'),
    (date(2019, 11, 15), 100, 'Transport'),
    (date(2019, 11, 16), 100, 'Transport'),
    (date(2019, 11, 10), 100, 'Transport'),
    ]

In each tuple are the date of expenditure, amount and expenditure type.每个元组中都有支出日期、金额和支出类型。 I'm required to print the expenditure type required and over the range of dates specified.我需要在指定的日期范围内打印所需的支出类型。 For example, i have to print out only tuples containing the expenditure type "Transport" and over the range of dates of 16 to 15 November.例如,我必须只打印包含支出类型“运输”的元组,并且在 11 月 16 日至 15 日的日期范围内。 I have no problems printing those of the specified type, or expenditures belonging to today.打印指定类型的那些,或属于今天的支出,我没有问题。 However i am having problem printing over a range of dates.但是,我在一系列日期打印时遇到问题。 How can i print only entries matching my specified range of dates?如何仅打印与我指定的日期范围匹配的条目?

You can try looping over them and comparing to start and end dates that you set beforehand:您可以尝试遍历它们并与您预先设置的开始日期和结束日期进行比较:

from datetime import date

expenditures = [(date(2019, 11, 16), 100, 'Transport'), (date(2019, 11, 15), 100, 'Transport'), (date(2019, 11, 16), 100, 'Transport'), (date(2019, 11, 10), 100, 'Transport')]

start = date(2019, 11, 15)
end = date(2019, 11, 16)

for expenditure in expenditures:
    if end >= expenditure[0] >= start:
        print(expenditure)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM