How should you define a regular expression to get the month and year numbers of a date in MySQL?

0

I would like to obtain the two numbers that correspond to the month of a date in dd-mm-yyyy format using MySQL.

So far this:

^\w{2}-("+month+")-+("+year+")$

Using Python, exchange month and year for the corresponding variables, leaving for example

^\w{2}-(11)-+(2018)$

Using an online RegExp test ( link )

When testing the dates 01/11/2018 , 05/11/2017 , the first one comes out as valid for that regular expression, for having the month and year searched.

When using it in MySQL using PHPMyAdmin, throw this:

SELECT * FROM 'jobs' WHERE 'date' REGEXP '^\w{2}-(11)-+(2018)$'
MySQL returned an empty result set (i.e. zero rows). (Query took 0.0004 seconds.)

The date data is these: 01/11/2018 and 05/10/2018

The date format is dd / mm / yyyy and is a 10-character string

In Python I get it this way:

datetime.today().strftime("%d/%m/%Y")
// 01/11/2018

How can I configure this regular expression to work correctly?

Additional Data:

I am currently saving the dates in that format using a varchar field.

For my application I use Flask-SQLAlchemy (extension ORM of Flask, microframework of Python).

So when doing the query I should use the following:

jobs = Job.query.filter(job.date.op("regexp")(regexp))

Where:

Job: is the class that represents the Job table.

Filter: acts as a where

op ("regexp") runs a regular expression

    
asked by Victor Alvarado 01.11.2018 в 19:02
source

1 answer

0

To solve the problem I resorted to the following:

1) Change the format of the saved data, in order for MySQL to recognize it as a date.

From dd / mm / yyyy to yyyy-mm-dd

2) Then, follow what is suggested by gbianchi:

SELECT MONTH(date) as month, YEAR(date) as year

3) In the case of sqlalchemy use extract, which will act as the MONTH and YEAR function

 filter(extract('year', MI_TABLA.date) == year)
 filter(extract("month", Mi_TABLA.date) == month)
    
answered by 09.11.2018 / 19:15
source