用Python从数组中提取到2007-1-1到2007-12-31?

Extracted from the array to 2007-1-1 to 2007-12-31 with Python?

看Python代码:

base = ['2018-1-9', '2017-1-1', '2017-4-10', '2015-2-15', '2017-12-31', '2018-1-8', '2017-12-31', '2017-4-10', '2017-3-16']
for item in base:
    if item <= '2017-12-31':
        print(item)

这导致

2017-1-1
2015-2-15
2017-12-31
2017-12-31

我想打印2017年的所有日期:

2017-1-1
2017-4-10
2017-12-31
2017-12-31
2017-4-10
2017-3-16

我的代码需要更改什么?

您比较的对象类型为 string 而不是 date。您可以查看 this link to learn how to compare dates. And this link 来检查如何根据字符串创建 date/datetime 对象。

请考虑以下代码:

Python 2.7.13 (default, Nov 23 2017, 15:37:09) 
[GCC 6.3.0 20170406] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> date1 = "2018-1-9"
>>> date2 = "2017-1-1"
>>> # converting strings into dates
>>> date1 = datetime.datetime.strptime(date1, "%Y-%m-%d").date()
>>> date2 = datetime.datetime.strptime(date2, "%Y-%m-%d").date()
>>> date1 <= date2
False
>>> date2 <= date1
True

首先,您需要使用 datetime 库将 string 转换为 date 对象。您需要提供日期格式才能正确转换(代码示例中的 %Y-%m-%d 部分)。拥有日期对象后,您可以使用比较运算符。

您应该将给定的字符串转换为日期对象并检查对象上的任何内容。

我建议你使用库 datetime 你可以阅读 the documentation and you can some examples.

对于您的代码,它需要:

base = ['2018-1-9', '2017-1-1', '2017-4-10', '2015-2-15', '2017-12-31', '2018-1-8', '2017-12-31', '2017-4-10',
        '2017-3-16']
max_date = datetime.strptime('2017-12-31', '%Y-%m-%d')
min_date = datetime.strptime('2017-1-1', '%Y-%m-%d')
for item in base:
    d = datetime.strptime(item, '%Y-%m-%d')
    if d <= max_date and d >= min_date:
        print(item)

结果是:

2017-1-1
2017-4-10
2017-12-31
2017-12-31
2017-4-10
2017-3-16