Nov-04-2020, 05:54 PM
(Nov-04-2020, 05:23 PM)deanhystad Wrote: I get a syntax error working with you code. Is there a paste error in you post? Why does the date time pattern appear twice?
No, I tested it again. Does work with Python 3.9 and should work with older versions.
Maybe the comments are confusing the repl, if you use copy&paste.
The parse_date was made twice to show:
- How to split tasks into smaller easier tasks -> better for testing. For example, you can use this function to test each line. No file for testing needed at all.
- How to catch Exceptions, handle them, retuning a default value for sorting.
To understand the sorting part, try this:
sort(sorted([1, 2, 3, 4, "a"]))
Error:TypeError Traceback (most recent call last)
<ipython-input-4-f654efc1df6a> in <module>
----> 1 sorted([1, 2, 3, 4, "a"])
TypeError: '<' not supported between instances of 'str' and 'int'
Same with datetime objects.This works because datetime is comparable with datetime:
sorted([datetime.min, datetime.max, datetime(2020,1,1), datetime(1990,1,1)])But this won't work:
sorted([datetime(2020,1,1), 1])
Error:TypeError: '<' not supported between instances of 'int' and 'datetime.datetime'
This is why a key-function for sorting should always return the same type.You could remove lines with wrong formatting before you sort.
Or you have a situation, where you want still to keep the lines with wrong format and sorting them.
There is no one universal solution for all.
Keep learning the basics before you switch to pandas.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!