I have a column with values '2015-02-14 12:23 AM' declared as varchar(150), I tried using to_date, convert and cast but not able to change the format. I would need this to filter on specific month/year/day. Thanks for the help
PS: Mysql instance is running on RDS through amazon AWS - not sure if its relevant
I suggest storing dates on proper date data type.
to_date is an Oracle function.
In MySQL, you can use STR_TO_DATE to converts a string to date then use Date_format to give the format you need
SELECT DATE_FORMAT(STR_TO_DATE(dt,'%Y-%m-%d %h:%i %p'),'%m/%Y/%d')
from test;
Demo
You can use substring with concat without the need of converting to date format:
select concat(substring(dt,6,2),'/', substring(dt,1,4),'/',substring(dt,9,2)) as my_date
from test;
Demo
SELECT CAST( SUBSTRING_INDEX( '2015-02-14 12:23 AM',
' ',
2
)
AS DATETIME
)
returns the datetime value. If you need to use this value in datetime context then you may remove CAST, it will be performed implicitly:
SELECT TIMESTAMPDIFF ( MINUTE,
SUBSTRING_INDEX( '2015-02-14 12:23 AM',
' ',
2
),
'2015-02-14 12:34'
)
Related
I currently have a mySQL database with two TEXT fields: Date and Time. These are in the format 'dd/mm/yyyy' and '0:00' respectively, for example '11/08/2020' and 19:12. I want to create a third field called Timestamp (of type INT) and convert the two original fields into this timestamp field and remove the date/time text fields.
I have done a bit of research in regards to using UNIX_TIMESTAMP() and STR_TO_DATE() but I can't seem to get it to work, the format seems to be wrong for it.
How can I achieve this in SQL and convert two string fields which represent date and time into a third field to replace them both which just stores the unix timestamp?
This is my best attempt so far..
SELECT UNIX_TIMESTAMP(STR_TO_DATE(CONCAT(`InfractionDate`, " ", `InfractionTime`), '%d %M %Y %h:%i%p')) FROM `playerinfractions`
The table is called playerinfractions and the date/time are stored in the TEXT fields InfractionDateand InfractionTime.
Many thanks in advance!
The format pattern that you use in the function STR_TO_DATE()is wrong.
Try this:
SELECT
UNIX_TIMESTAMP(
STR_TO_DATE(
CONCAT(`InfractionDate`, ' ', `InfractionTime`),
'%d/%m/%Y %H:%i')
)
FROM `playerinfractions`
You need to tell STR_TO_DATE the correct format of your date and time, which you suggested was '%d/%m/%Y %H:%i'
SELECT UNIX_TIMESTAMP(
STR_TO_DATE(
CONCAT('10/08/2020', ' ', '12:20'), '%d/%m/%Y %H:%i' )
)
)
FROM `playerinfractions`
So using your columns
SELECT UNIX_TIMESTAMP(
STR_TO_DATE(
CONCAT(`InfractionDate`, ' ', `InfractionTime`), '%d/%m/%Y %H:%i' )
)
)
FROM `playerinfractions`
I tried passing a string to the same function in below format and it worked. Also you can share your format to check it further.
select UNIX_TIMESTAMP(STR_TO_DATE(CONCAT('8/12/2020',' ', '12:01:49' ),'%m/%d/%Y %h:%i:%s'))
I have a MySQL DB to work with which has a LASTUPDATE column as VARCHAR.
This field has this format: YYYY-MM-DD HH:mm:ss
I need to set up a SELECT query to find all rows after e certain date, so i was trying to use the CONVERT function in this way
SELECT * from POWER WHERE CONVERT(DATETIME, LASTUPDATE) > 'CONVERT(DATETIME, '2016-12-29 17:24:22')'
but i'm getting the error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LASTUPDATE) > 'CONVERT(DATETIME, '2016-12-29 17:32:52')'' at line 1
I have also tried to use:
SELECT * from POWER WHERE CONVERT(DATETIME, LASTUPDATE) > '2016-12-29 17:32:52' but i'm getting the same error
You could use the str_to_date
SELECT *
from POWER
WHERE str_to_date(LASTUPDATE, '%Y-%m-%d %H:%i:%s' ) >
str_to_date('2016-12-29 17:24:22', '%Y-%m-%d %H:%i:%s' )
Use str_to_date()
The query should use str_to_date() like this. See MySQL Manual for more details
SELECT
*
from POWER
WHERE
str_to_date(LASTUPDATE, '%Y-%m-%d %H:%i:%s') > '2016-12-29 17:24:22'
Date and time literial
Note that MySQL accepts date and time literals, so you do not need another str_to_date on the right-hand side of the > operator. See this for more details.
About the form between ... and ... on a string field storing date value
Some suggested using the form of between ... and ..., such as the one
shown below. Note that this method would work only if the string
values happen to use a format in which sorting the string alphabetically (in the given collation) happens to give the same sorting order as date (the format used in the original question -- '%Y-%m-%d %H:%i:%s' -- happens to satisfy this condition, but this is not guaranteed (see an example below) for many string representations of date/time values).
SELECT
*
from POWER
WHERE
LASTUPDATE between '2016-12-29 17:24:22' AND '2016-12-31 23:59:59';
And it would fail if the string values are using a different format, such as these:
create table power (
lastupdate varchar(40) not null default ''
) engine=innoDB;
insert into power
values
('Dec 30, 2016 07:24:22')
, ('Jan 28, 2016 07:24:22')
For the above, we must still use the str_to_date() function (this time with a format argument %b %d, %Y %H:%i:%s that is matching the format used with the string values)
SELECT
*
from POWER
WHERE
str_to_date(LASTUPDATE, '%b %d, %Y %H:%i:%s') > '2016-12-29 17:24:22';
I have an sqlfiddle.com page showing the above example.
convert is an MS-SQL Server function. In MySQL, you can use the str_to_date function with similar semantics:
SELECT *
FROM power
WHERE STR_TO_DATE(lastupdate, '%Y-%m-%d %H-%i-%s') >
STR_TO_DATE('2016-12-29 17:24:22', '%Y-%m-%d %H-%i-%s')
Hi I will use mysql db in my project. The database using with php now. I will use with asp.net. Tables have data column and date like this : 1289053800.
How can I convert this value to .net datetime.
Regards
It seems your date time values are stored in UNIX_TIMESTAMP format.
You can use FROM_UNIXTIME on them to convert to regular datetime type.
select
date_cloumn -- that has 1289053800 kind of values
, from_unixtime( date_cloumn ) as dt_f_ut
, date_format( from_unixtime( date_cloumn ), '%d.%m.%Y %h.%i' ) as dt_f_ut_12hr
, date_format( from_unixtime( date_cloumn ), '%d.%m.%Y %H.%i' ) as dt_f_ut_24hr
from table_name
;
Using .Net, you may need no changes but just read:
a DateTime on dt_f_ut or
a String on dt_f_ut_12hr or
a String on dt_f_ut_24hr or
into desired variables.
Demo # MySQL 5.5.32 Fiddle
Refer to:
FROM_UNIXTIME()
Format UNIX timestamp as a date
UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
Return a UNIX timestamp
select DATE_FORMAT('8:48:30 AM', '%H:%i:%s')
It returns Null why ?
but when using
select DATE_FORMAT(CURTIME(), '%H:%i:%s')
It return formatted value.
It's returning NULL because MySQL isn't successfully parsing the string into a valid DATETIME value.
To fix the problem, use the STR_TO_DATE function to parse the string into a TIME value,
SELECT STR_TO_DATE('8:48:30 AM', '%h:%i:%s %p')
Then, to get the TIME value converted to a string in a particular format, use the TIME_FORMAT function, e.g. 24-hour clock representation:
SELECT TIME_FORMAT(STR_TO_DATE( '8:48:30 AM', '%h:%i:%s %p'),'%H:%i:%s')
returns:
--------
08:48:30
The method DATE_FORMAT is used to display date and time, however in the first you are not assigning any date except time, so its is throwing null.
From the manuals -
DATE_FORMAT Formats the date value according to the format string.
In MySql version 5.5 SELECT DATE_FORMAT( CURTIME( ) , '%H:%i:%s' ) returns null
DATE_FORMAT 's first parameter is of type DATETIME. On recent mysql server versions both your queries return NULL.
So the answer to your question is that this difference in behaviour is because of a bug in your mysql version - in some way it converts the TIME to DATETIME, while it cannot convert the string to DATETIME.
Here is also an example of a working query:
select DATE_FORMAT(NOW(), '%H:%i:%s')
NOW() returns a DATETIME while CURTIME() returns TIME.
To my knowledge, I think it's because MySQL recognises the function as a time, and therefore knows how to handle it. Whereas, in the first example, it regards it as a string and doesn't know what to do with it.
Is there way in MySQL to create DATETIME from a given attribute of type DATE and a given attribute of type TIME?
Copied from the MySQL Documentation:
TIMESTAMP(expr), TIMESTAMP(expr1,expr2)
With a single argument, this function returns the date or datetime expression expr as a datetime value. With two arguments, it adds the time expression expr2 to the date or datetime expression expr1 and returns the result as a datetime value.
mysql> SELECT TIMESTAMP('2003-12-31');
-> '2003-12-31 00:00:00'
mysql> SELECT TIMESTAMP('2003-12-31 12:00:00','12:00:00');
-> '2004-01-01 00:00:00'
To get a true DATETIME value from your two separate DATE and TIME values:
STR_TO_DATE(CONCAT(date, ' ', time), '%Y-%m-%d %H:%i:%s')
You could use ADDTIME():
ADDTIME(CONVERT(date, DATETIME), time)
date may be a date string or a DATE object.
time may be a time string or a TIME object.
Tested in MySQL 5.5.
datetime = CONCAT(date, ' ', time);
select timestamp('2003-12-31 12:00:00','12:00:00');
works, when the string is formatted correctly. Otherwise, you can just include the time using str_to_date.
select str_to_date('12/31/2003 14:59','%m/%d/%Y %H:%i');
Without creating and parsing strings, just add an interval to the date:
set #dt_text = '1964-05-13 15:34:05.757' ;
set #d = date(#dt_text) ;
set #t = time(#dt_text) ;
select #d, #t, #d + interval time_to_sec( #t ) second;
However this truncates the microseconds.
I agree with Muki - be sure to take account of time zones and daylight savings time!