mysql - Python - Regular Expression to find dates in list -
while looping through csv i'm attempting normalize dates mysql load (yyyy-mm-dd). i've attempted search items contain 2 forward slashes, i've found that's not unique enough identify date. can accomplished regular expression , looking items match pattern? input appreciated.
example input:
['1','2','01/02/2015','3','4','1-05-2015','5','anot/her ex/ample','6']
example output:
['1','2','2015-01-02','3','4','2015-01-05','5','anot/her ex/ample','6']
if know order of fields. can use datetime.strptime:
from datetime import datetime l = ['1','2','01/02/2015','3','4','1-05-2015','5','another ex/ample','6'] out = [] ele in l: try: out.append(datetime.strptime(ele,"%d/%m/%y").strftime("%y-%m-%d")) except valueerror: out.append(ele) print(out)
i have no idea how expect '1-05-2015'
become '2015-01-05'
considering forward slashes dates:
if have multiple patterns test:
out = [] ele in l: patt in ["%d/%m/%y","%d-%m-%y"]: try: p1 = datetime.strptime(ele,patt).strftime("%y-%m-%d") if p1: out.append(p1) break except valueerror e: print(e) else: out.append(ele) print(out) ['1', '2', '2015-01-02', '3', '4', '2015-01-05', '5', 'anot/her ex/ample', '6']
you can filter on length , try parse correct length strings:
for ele in l: ln = len(ele) if 7 <= ln > 10: out.append(ele) continue patt in ["%d/%m/%y", "%d-%m-%y"]: try: p1 = datetime.strptime(ele,patt).strftime("%y-%m-%d") if p1: out.append(p1) break except valueerror e: print(e) else: out.append(ele)
a regex potentially going match lot more dates unless 100 percent should @ least try casting regex returns datetime object before adding.
Comments
Post a Comment