0

I have a list of dates in python for example

dates = ["01/03/2010", "02/11/2010", "05/12/2010", "21/12/2010"]

in dd/mm/yyyy format. Then I have a cut-off date "30/11/2010", so I want all dates up to "30/11/2010" from dates, so the output would be

["01/03/2010", "02/11/2010"]

I have tried searching for similar questions but they all seem to be iterating through ranges of dates. Is there any way this can be done in Python?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Beck
  • 5
  • 3
  • Can you show the code you have tried to use and explain how it failed? – mkrieger1 Jul 24 '20 at 00:27
  • "iterating through ranges of dates" does not seem terribly wrong, depending on what exactly you mean by that. – mkrieger1 Jul 24 '20 at 00:27
  • You have to iterate over the strings in the `dates` list, convert each to a "date" object which you can compare to the cut-off date (which you need to have converted as well so you can compare it), and if it is "smaller" add it to the result list. Which part of this did you have trouble with? – mkrieger1 Jul 24 '20 at 00:30
  • 1
    Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – mkrieger1 Jul 24 '20 at 00:31
  • @mkrieger1 Im not sure how to compare the dates, I have converted them using datetime.strptime using "%d/%m/%Y" , but im unsure how the comparison between dates would work. – Beck Jul 24 '20 at 00:38
  • Using the `<` operator. See https://stackoverflow.com/questions/8142364/how-to-compare-two-dates – mkrieger1 Jul 24 '20 at 00:39

1 Answers1

0

If you're doing anything with the dates other than immediately printing them out again, you probably want to convert them to date objects.

import datetime as dt

dates = ["01/03/2010", "02/11/2010", "05/12/2010", "21/12/2010"]
parsed_dates = [dt.datetime.strptime(d, "%d/%m/%Y").date() for d in dates]
filtered_dates = [d for d in parsed_dates if d <= dt.date(2010, 11, 30)]
output_dates = [d.strftime("%d/%m/%Y") for d in filtered_dates]
print(", ".join(output_dates))
Jiří Baum
  • 6,697
  • 2
  • 17
  • 17