Date/time scaning with Python regular expressions
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

Im looking for an approach to scan a line for a date time substring. The date time substring could appear anywhere in the string. If detected convert to a python datetime. The code below does not work.

import re
import datetime
line="07/12/18 00:02:55 - Process(28389.1166381) User(mqsystem) Program(amqrmppa)"
match = re.search('\d{2}/\d{2}/\d{2}d{2}:d{2}:d{2}', line)
print(match)
if match is not None:
    dte = datetime.datetime.strptime(match.group(), '%m/%d/%y %H:%m:%s').date()
    print(dte)
awarded to kostasx
Tags
regex
python3

Crowdsource coding tasks.

3 Solutions

Winning solution

import re
import datetime
line="07/12/18 00:02:55 - Process(28389.1166381) User(mqsystem) Program(amqrmppa)"

match = re.search(r'\d{2}/?\d{2}/?\d{2,4} \d{2}:\d{2}:\d{2}', line)

if match is not None:
    dte = datetime.datetime.strptime(match.group(), '%m/%d/%y %H:%M:%S').date()
    print(dte)

If your line can contains many date time, you can use findall method :

match = re.findall('(\d{2}/\d{2}/\{2-4}+ \d{2}:\d{2}:\d{2})', line)

this will result to a list of strings that contains all your dates of your line

for dte in match:
    mydate = datetime.datetime.strptime(dte, '%d/%m/%y %H:%M:%S').date()
    print mydate

Be careful of the /d /m when parsing your date, it depends if you are using english format (%m/%d) or french (%d/%m), I have had issues with that.


Hi, you had some regex and date format issue, the below is the fixed version of your script and it is now working fine:

import re
import datetime
line="07/12/18 00:02:55 - Process(28389.1166381) User(mqsystem) Program(amqrmppa)"
match = re.search('\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}', line)
print(match)
if match is not None:
dte = datetime.datetime.strptime(match.group(), '%m/%d/%y %H:%M:%S').date()
print(dte)

View Timeline