I have dates in a Python script that I need to work with that are in a list. I have to keep the format that already exists. The format is YYYY-MM-DD. They are displayed in the form [‘2010-05-12’, ‘2011-04-15’, ‘Date’, ‘2010-04-20’, ‘2010-11-05’] where the order of the dates appears to be random and they are made into lists with seemingly insignificant lengths. The length of this data can get very large. I need to know how to sort these dates into a chronological order and omit the seemingly randomly placed entries of ‘Date’ from this order. Then I need to be able to perform math operations such as moving up and down the list. For example if I have five dates in order I need to be able to take one date and be able to find a date x spaces ahead or behind that date in the order. I’m very new to Python so simpler explanations and implementations are preferred. Let me know if any clarifications are needed. Thanks.
Share
You are asking several questions at the same time, so I’ll answer them in order.
To filter out the
"Date"entries, use thefilterfunction like this:Or perhaps like this, using Python’s list comprehensions, if you find it easier to understand:
You might want to convert the data types of the date items in your list to the
dateclass to get access to some date-related methods like this:And to sort the dates you simply use the
sortmethodThe syntax in Python for accessing items and ranges of items in lists (or any “sequence type”) is quite powerful. You can read more about it here. For example, if you want to access the last two dates in your list you could do something like this:
If you put it all together you’ll get something like this: