Question

Is there any way, how to parse line which contains date in some format and value? I'm looking for general solution. I'm writing script, which should validate string. My input is some string and time format. For example:

in first file and known time format

[10:17:21 20.04.1911] 890.584
[%H:%M:%S %d.%m.%Y]

in second file and known time format

10:17:21-20.04.1911 890.584
%H:%M:%S-%d.%m.%Y

in third file and known time format

(20-04-1911) 890.584
(%d-%m-%Y)

in fourth file and known time format

20-04-1911 10:17:21 890.584
%d-%m-%Y %H:%M:%S

etc.
I already have function to get timestamp from date according to time format, but I don't know, how to parse date from that line.
Any ideas? Thanks.

Was it helpful?

Solution

I would use try here:

import datetime

def parse_date(line):
    for template, length in [("[%H:%M:%S %d.%m.%Y]", 21), 
                             ("%H:%M:%S-%d.%m.%Y", 19), ...]:
        try:
            return datetime.datetime.strptime(line[:length], template)
        except ValueError:
            pass

This will work through all the templates, return a datetime object if it can extract one from the line and return None if none of the templates match.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top