TransWikia.com

How to get all dates up to a certain date?

Stack Overflow Asked by Beck on February 18, 2021

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?

One Answer

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))

Answered by sabik on February 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP