Searching date and and time from a text file

Daniel Schüle uval at rz.uni-karlsruhe.de
Mon Nov 14 23:36:45 CET 2005


masudtarek at gmail.com wrote:
> Hi, I am new in Python programming. Can anybody give me any idea about
> how to detect more than one date and time (like 11/11/2005 ,
> 10-12-2006, 12:30 etc) from a text file and keep them in a list.

well first we read the file

src = file("/your/file").read()

then we need some regular expressions to find the date and time

import re

pattern = {
	"time" : re.compile(r"\b\d\d:\d\d\b"),
	"date1" : re.compile(r"\b\d\d-\d\d-\d\d\d\d\b"),
	"date2" : re.compile(r"\b\d\d/\d\d/\d\d\d\d\b")
}

times = pattern["time"].findall(src)
dates1 = pattern["date1"].findall(src)
dates2 = pattern["date2"].findall(src)

note this is not very good solution though
one should check all the items to be sure
hours are between 0 and 23 and minutes in
range 0 .. 59

for time in times:
	t = time.split(":")
	assert 0 <= int(t[0]) <= 23
	assert 0 <= int(t[1]) <= 59


hth, Daniel
ps: all code untested




More information about the Python-list mailing list