-1

I have 3 possible string date.

I have to parse the date string with Regex

date = "13.06.2020"
date2 = "13-06-2020"
date3 = "13/06/2020"
for i in [date,date2,date3]:
    finder = re.findall(r'something',i) #I try findall but I think it doesn't work.
    print("day : " + finder[0])
    print("month : " + finder[1])
    print("year : " + finder[2])

It supposed to give that output for all possibilities. I figure out with Datetime but I can't use it. I have use re library

day:13
month:06
year:2020

Do you guys have any suggestions?

Murat Demir
  • 716
  • 7
  • 26

2 Answers2

0

Try this

for i in [date,date2,date3]:
    finder = re.findall(r'(\d{1,2})[\.\-\/](\d{2})[\.\-\/](\d{4})',i)
    print("day : " + finder[0][0])
    print("month : " + finder[0][1])
    print("year : " + finder[0][2])
SeemsLegit
  • 97
  • 3
0

Avoid using regex to parse date strings. Use parser.parse from dateutil module (which you can install through pip using the cmd pip install python-dateutil)

>>> from dateutil import parser
>>> for date_str in [date,date2,date3]:
...     dt = parser.parse(date_str)
...     print(f"day : {dt.day}, month: {dt.month}, year: {dt.year}")
... 
day : 13, month: 6, year: 2020
day : 13, month: 6, year: 2020
day : 13, month: 6, year: 2020
Prem Anand
  • 2,469
  • 16
  • 16