开发者

read a text field in Python using regular expressions

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:)

Bt开发者_StackOverflow中文版w, how to parse the date?

Thanks!


#!/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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜