from datetime import datetime def parse_datetime(line): date_str, _ = line.split(maxsplit=1) date_fmt = "%Y/%m/%d:%H:%M:%S" return datetime.strptime(date_str, date_fmt) with open("in.txt") as fd: for line in sorted(fd, key=parse_datetime, reverse=True): # line is still a str print(line.strip()) # print(line, end="")This will still fail with corrupt data.
You can catch these errors and return
datetime.min
, which is the earliest possible date represented by datetime.def parse_datetime(line): date_fmt = "%Y/%m/%d:%H:%M:%S" try: date_str, _ = line.split(maxsplit=1) return datetime.strptime(date_str, date_fmt) except ValueError: # invalid format return datetime.min # datetime.min == datetime.datetime(1, 1, 1, 0, 0) # used as minimum value # you can't mix if you sort, so all elements must be a datetime
fd
(the file object) is an iterator. Iterating over thefd
will split the lines.
sort(fd)
will sort all lines of the whole file in lexicographical order.
- The key function of
sort
return adatetime
object.
- sorting requires comparison. Python has a strong TypeSafety, so you can't for example compare an
int
with astr
. But you can ship around with the key function, which always return the same type.
If you want to put the data into a data-structure (e.g. a dict or namedtuple), I would do the parsing first, put this data into a list and sort the list, when everything has been finished.
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!