-2

Look at the Python code:

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)

This results in

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

I want to print all the dates in 2017:

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

What needs to be changed in my code?

Green
  • 2,405
  • 3
  • 22
  • 46
wen tian
  • 433
  • 2
  • 5
  • 18
  • if you want to compare dates as strings, make sure they are built as YYYY-MM-DD (es. base = ['2018-01-09', '2017-01-01', '2017-04-10', '2015-02-15', '2017-12-31', '2018-01-08', '2017-12-31', '2017-04-10', '2017-03-16')] – Don Jan 10 '18 at 11:29
  • You should also test item >= "2017-01-01" – Don Jan 10 '18 at 11:30
  • 1
    FYI It better practice to also try to understand the answers. this how you can develop your coding skills (i.e. read the documentation attached etc.) – Green Jan 10 '18 at 12:01

2 Answers2

0

You are comparing objects of type string instead of date. You can look at this link to learn how to compare dates. And this link to check how to create date/datetime object based on the string.

Please consider the code below:

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

First, you need to convert your string into date object using datetime library. You need to provide date format in order to convert it properly (part %Y-%m-%d from code example). After you have your date object you can use comparing operators.

Laszlowaty
  • 1,295
  • 2
  • 11
  • 19
0

You should turn the given strings to a date object and check what ever you like on the object.

I would suggest you to use the library datetime you can read about the documentation and you can some examples.

For your code it would like:

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)

the result is:

2017-1-1
2017-4-10
2017-12-31
2017-12-31
2017-4-10
2017-3-16
Green
  • 2,405
  • 3
  • 22
  • 46