tags:

views:

64

answers:

3

I have text file, like

FILED AS OF DATE:       20090209
DATE AS OF CHANGE:      20090209

I need to find the position using FILED AS OF DATE: and read the date. I know how to do it using python strings. But using a regular expression seems cooler:)

Btw, how to parse the date?

Thanks!

+1  A: 

Is this what you need?

/FILED.*([0-9]{4})([0-9]{2})([0-9]{2})$/

Search for FILED then anything then parses date divided in 3 groups.

Lex
+2  A: 
#!/usr/bin/env python
import datetime, fileinput, re

for line in fileinput.input():
    if 'FILED AS OF DATE' in line:
       line = line.rstrip()
       dt = datetime.datetime.strptime(line, 'FILED AS OF DATE:       %Y%m%d')

       # or with regex
       date_str, = re.findall(r'\d+', line)
       dt = datetime.datetime.strptime(date_str, '%Y%m%d')

       print dt.date()

Example:

$ ./finddate.py input.txt

Output:

2009-02-09
J.F. Sebastian
Get just the numbers. Good simple idea, but I think that adding a little comment will make the post even better!
Khelben
+1  A: 

You really do not need to use RE for this.

Regarding parsing date, you can use datetime.strptime(date_string, format). Then you can convert it from datetime.datetime to datetime.date if required.

Alternatively use python-dateutil parse() function, which is quite handy when the format of your date(time) value is not fixed.

van