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.
Related
Hi I'm writing queries for MySQL, and now my database has a column containing the timestamp in this format: 7/14/2015 7:57:49 AM, but I need to use the DATEDIFF function, so how can I convert the timestamp into the format like: 2015-7-14 (or 2015-07-14, I'm not sure which one is correct; just the date)?
This should convert your string to just the date in a date format, then you can use DATEDIFF on the date fields in question:
SELECT STR_TO_DATE(LEFT(t,LOCATE(' ',t) - 1), '%m/%d/%Y') FROM my_table;
The LEFT function will take the substring to the left of the space, which is just your date, then STR_TO_DATE will convert that substring to a date the system can use.
(Not knowing your field and table names, I used t and my_table.)
You don't need to. The way MySQL displays timestamps has nothing to do with the way they're stored internally; as long as it's TYPE TIMESTAMP or some compatible type, the DATEDIFF() function will know what to do with it.
TIMESTAMPs are actually stored as a really huge integer representing (I think) milliseconds from Midnight UTC, January 1st, 1970. The display format is determined by a system global variable, and has nothing to do with the actual value.
Converting from a string to a DATETIME or TIMESTAMP is actually also fairly straightforward using the STR_TO_DATE() function; in your case the format string would be something like
STR_TO_DATE('%c/%e/%Y %l:%i:%s %p', datecol)
although you might have to experiment a bit to make it work reliably.
I have a table with a varchar column DateFrom that has this format:
2014-02-22T08:08:00
I want an sql that prints 08:08 and one that prints 22-02-2014 but i can't seem to get the time function to work.
What i'm trying to do is get all entries in DateFrom and print them as just time (HH:MM)
and the same with date.
Altough I think string functions are a better option in this case (like #hakre answered) and less cpu expensive, you can also achieve this goal using the STR_TO_DATE, DATE and TIME function.
SELECT
DATE(STR_TO_DATE('2014-02-22T08:08:00', '%Y-%m-%dT%H:%i:%s')),
TIME(STR_TO_DATE('2014-02-22T08:08:00', '%Y-%m-%dT%H:%i:%s'))
If you're not looking for date/time but for string functions, they are available here:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
One string function that I think is useful for your substring operation is SUBSTRING. You can tell per the varchar column that you want a sub-string starting from a position for a certain length with it:
SUBSTRING(DateFrom FROM 1 FOR 8) AS DateName -- "2014-02-22"
SUBSTRING(DateFrom FROM 10 FOR 5) AS TimeName -- "08:08"
Use other string functions to concatenate parts in the order you need it.
Alternatively you can cast your varchar string in that format to a datetime type and then format as needed:
CAST(DateFrom AS datetime)
See the Mysql manual for more information about casting types and the date-time functions that are available:
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
SQL Example:
SET #DateFrom = '2014-02-22T08:08:00';
SELECT DATE(CAST(#DateFrom AS datetime)); -- '2014-02-22'
SELECT TIME(CAST(#DateFrom AS datetime)); -- '08:08:00'
I have this query
SELECT *
FROM `users_profile`
WHERE DATE_FORMAT(dob,'%d-%m-%Y') BETWEEN '05-03-1996' AND '05-03-1915'
which should return two results which both have these dates in the dob column
08-02-1996
14-02-1996
But it dosen't return anthing!! What am I doing wrong!!??
Why would you take a perfectly good date and convert it to a (bad) string for comparison?
Do the comparison as dates and put the constants in the right order:
SELECT *
FROM `users_profile`
WHERE dob BETWEEN date('1915-03-05') and date('1996-03-05');
Also note that I changed the date format for the date constants to YYYY-MM-DD. This is the ISO standard format for dates. (Despite that), it is a really good idea to use.
I am assuming that dob really is a date, because that is what the function date_format() takes for its first argument.
I need to convert varchar string data to time format in mysql.
For example,
I have a varchar column in table which stores time. The accepted values should be like 9:30 AM or 1200 PM. But currently it has either blank values or it has values like 9.30am or 12:00
There are many records like this, so cannot update manually.
Ithere any work around or function or procedure to do so?
please help.
Thanks
You can use the STR_TO_DATE() MySQL function to convert any string to a date.
Additionally you can use TIME() to extract the time portion of a datetime. A combination of both function is used to convert an arbitrary date string to a datetime and then you can extract the time portion from it as a valid MySQL TIME.
By default MySQL functions follow standard format but custom format can be specified and if your values don't use the international formats you'll need to check with the documentation and provide the format your system is using.
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','-','');