0

I have a case where I have to extract date from a SQL query that I am running through a python script.

This is the query:

select * from COLL_DS2 where TRANSACTION_DATE between '2021.02.28' and '2021.04.08' order by CREATION_DATE

I want to extract '2021.02.28' and '2021.04.08' from the query string.

Any help please? Thanks in advance

1
  • Can you please share your code for better understanding Commented Apr 11, 2021 at 8:22

2 Answers 2

1

Another way to write it. Tim Biegeleisen solution is good, just need to add the import re

import re
Query = "select * from COLL_DS2 where TRANSACTION_DATE between '2021.02.28' and '2021.04.08'"
ldat = re.findall('\d+\.\d+\.\d+', Query)

print(ldat)
# ['2021.02.28', '2021.04.08']
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, this one working. Thanks. In the above solution, I was getting an empty array.I already had re imported. I think it was because of r in the "re.findall" line which was causing the problem.
This is not the best or safest answer which can be given, because the regex pattern used here would match things like IP addresses e.g. 192.168.0.1 in addition to dates.
You are right for IP adresses but on the other hand you have also many format for dates : 2021.4.8, 21.4.8 etc...
1

You may use re.findall:

sql = "select * from COLL_DS2 where TRANSACTION_DATE between '2021.02.28' and '2021.04.08' order by CREATION_DATE"
dates = re.findall(r"'(\d{4}\.\d{2}\.\d{2})'", sql)
print(dates)  # ['2021.02.28', '2021.04.08']

3 Comments

Sorry it's returning an empty list.
@amiteshshukla No it's not.
I think it was because of r in the "re.findall" line which was causing the problem. The below answer is the updated version of your answer. But that one worked for me. So marked that one as right and upvoted your answer. Thanks for giving the solution though. Much appreciated @Tim Biegeleisen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.