How can I extract the month with a sql query in mysql.
The date format is as follows: dd/mm/yyyy.
MONTH(datecol) = $month // this does not work.
However if I change the date format to yyyy-mm-dd it works, but this is not an option.
You can parse a date in any format into an SQL date value with str_to_date. For example:
select month(str_to_date('25/07/2013', '%d/%m/%Y'));
This expression will extract the portion of the string that appears between the first and second forward slashes.
SUBSTRING_INDEX(SUBSTRING_INDEX( '25/07/2013' ,'/',2),'/',-1)
will return '07'
To get this converted to a numeric, add zero to it,
SUBSTRING_INDEX(SUBSTRING_INDEX( '25/07/2013' ,'/',2),'/',-1) + 0
will return a numeric value of 7
NOTES
This expression will work with any string value, not just strings representing a valid date in the specified format. For example:
SUBSTRING_INDEX(SUBSTRING_INDEX( 'dd/mm/yyyy' ,'/',2),'/',-1)
will return 'mm'
If only one slash is found in the string, this will return the portion following the slash. If no slashes are found in the string, this will return the entire string.
If your intent is to validate that the string represents a valid date value, in the specified format, then the STR_TO_DATE() function can be used to convert the string to a DATE. The return from that expression can be used as an argument to any of the MySQL functions that take a DATE argument, such as the MONTH() function in your sample question.
Related
Is there a way to convert a string such as "-1 week" or "-5 minutes" into a datetime value in MySQL similar to php's extremely convenient strtotime() function?
I have a table that stores a human-readable time interval (such as "2 minutes") in one column and a datetime in another column.
I would like to select the rows where more than the amount of time specified in interval has elapsed since datetime.
MySQL doesn't have an equivalent of PHP's strtotime() in the sense that there is nothing that will automatically attempt to parse and determine the format of a date string using by assuming multiple formats.
What it does have is STR_TO_DATE(str,format) which requires you specify the format of your date, time or date + time string. It is the equivalent of PHP's date_create_from_format(format, str) function (though the format of the format parameter are different).
Here are some examples given from the MySQL documentation. They show a date being passed along with the format string that lets it know how the date string is to be interpreted:
SELECT STR_TO_DATE('01,5,2013','%d,%m,%Y');
SELECT STR_TO_DATE('May 1, 2013','%M %d,%Y');
Alternatively, you can cast a string to a date, time or datetime type, but they require a specific format (YYYY-MM-DD hh:mm:ss.fraction) for it to work:
SELECT CAST("2019-11-21" AS DATE);
If you deviate too far from that format it will make a few assumptions but could produce an incorrect date.
I am trying to convert a column in a BQ table to timestamp. I have two string columns, one for utc_hour (string 0-23) and utc_day (string yyyymmdd) imported from a public data source. I merged the two columns to produce a string column, utc_timestamp, with strings like this - "20171208 500" .
I need to convert that string into timestamp, and when I use
TIMESTAMP(utc_timestamp)
I get the error message
Invalid timestamp: '20171208 500'
I tried using dataprep, which also could not convert that string to a timestamp.
How can I convert this format to a timestamp?
Try to parse with %Y%m%d%k%M format.
PARSE_TIMESTAMP("%Y%m%d%k%M", utc_timestamp)
This question is already answered but in case someone else visits here with his/her own unique timestamp format (in which case the accepted answer might not work), you need to follow the notations on this documentation page
For eg, in my case values were like this 2020-05-11-00:00:00. So, I went to the above-mentioned page and found that the format string that I needed would be something like %Y-%m-%d-%H:%M:%S.
I will put the description for the ones that I used in my format string:
%d The day of the month as a decimal number (01-31).
%H The hour (24-hour clock) as a decimal number (00-23).
%M The minute as a decimal number (00-59).
%m The month as a decimal number (01-12).
%S The second as a decimal number (00-60).
%Y The year with century as a decimal number.
The :s and the -s are quite self-explanatory.
This is my string value 20180421
I want to convert this value into 2018/04/21
here my code
$querya="SELECT STR_TO_DATE('$date','%m/%d/%Y');";
but i does not change my string
Your format is already in ISO format, so you can just use date() for the conversion:
select date(?)
You can also use str_to_date() but you need to use the correct format:
$querya = "SELECT STR_TO_DATE(?, '%Y%m%d')";
Note the use of ?. This is a parameter placeholder and indicates that you should pass the value in as a parameter rather than as a variable.
I should point out that 2018/04/21 is a particular format. Dates are stored in an internal format. To get a particular output format, you need to convert them to strings. Here is one solution:
select date_format(date(?), '%Y/%m/%d')
The date() function is optional, because MySQL will correctly convert this string to a date, so you can also use:
select date_format(?, '%Y/%m/%d')
How can I convert a string name into the actual month number. For instance if I have a string as 'March', how can this be converted to 3.
I know that this can be done using a case statement but then I want to know if there is any predefined function that can do this conversion.
select date_format(str_to_date('March','%M'),'%c')
firstly, using str_to_date to convert string to month name, and then format the month name to number format
month(str_to_date(MonthField,'%M'))
For more information about month and str_to_date, you can check the link
example for above is select month(str_to_date('March','%M')) from dual;
will give the result 3
Use the STRING_TO_DATE function:
SELECT STRING_TO_DATE('March','%M')
See the (function reference](https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_str-to-date).
See the date formatting codes reference.
Following is my sql query kindly let me know why is it returning null
Select STR_TO_DATE ('11-APR-74','%e%b%Y')
OR
Select DATE_FORMAT ('11-APR-74','%e%b%Y')
From MySQL STR_TO_DATE function:
The server scans str attempting to match format to it. ... Scanning
starts at the beginning of str and fails if format is found not to
match.
This is why your first query fails: 11-APR-74 does not look like %e%b%Y, so date cannot be parsed. You should do instead
SELECT STR_TO_DATE ('11-APR-74','%e-%b-%Y')
From MySQL Date and Time types:
Although MySQL tries to interpret values in several formats, date
parts must always be given in year-month-day order (for example,
'98-09-04'), rather than in the month-day-year or day-month-year
orders commonly used elsewhere (for example, '09-04-98', '04-09-98').
This is why your second query fails: 74 is not a valid day of month, you should do instead
SELECT DATE_FORMAT ('74-APR-11','%e%b%Y')
Note, that DATE_FORMAT is usually used on DB values, not string literals as you do - to get an output different from the default one.
If you want to convert from string to date
Select STR_TO_DATE ('11-APR-74','%d-%b-%y')
use it like ::
Select STR_TO_DATE ('11-APR-74','%e-%b-%Y')
Because '%e%b%Y' format does not correspond to '11-APR-74' string value (as STR_TO_DATE function expects), and because '11-APR-74' value is of type CHAR, but not DATETIME (as DATE_FORMAT function expects).
If you want to reformat a date represented by a CHAR value, convert it from its original format to DATETIME first, and then convert it to a string of desired format:
SELECT DATE_FORMAT(STR_TO_DATE('11-APR-74','%e-%b-%Y'),'%e%b%Y');
By the way, you could strip dashes with a plain string sunction:
SELECT REPLACE('11-APR-74','-','');