-1

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.

Majzlik
  • 199
  • 1
  • 3
  • 13
  • hi! what have you tried in terms of regular expressions? – arturomp May 13 '14 at 17:21
  • possible duplicate of [How can I parse a time string containing milliseconds in it with python?](http://stackoverflow.com/questions/698223/how-can-i-parse-a-time-string-containing-milliseconds-in-it-with-python) – ElGavilan May 13 '14 at 17:21
  • Do you mean use regex to copy match to variable? Don't you have any example? – Majzlik May 13 '14 at 17:25
  • @ElGavilan it's not duplication, I have only whole string, which contains date and value. I don't know, how get just date. – Majzlik May 13 '14 at 17:28

1 Answers1

1

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Thats it! It works fine, except of len(template). If there is %Y in date formate template, it means 4 character (full year) so I have to make a condition, but thats no problem. – Majzlik May 13 '14 at 18:07
  • Ah, sorry. Rather than a conditional, you could have a list of tuples `(template, length)` and iterate over those pairs. – jonrsharpe May 13 '14 at 18:17