Creating DATETIME from DATE and TIME - mysql

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!

Related

Converting string to datetime split into date and time

I am trying to convert string '2022-12-28T22:28:43.260781049Z' to datetime format.
I have such query:
SELECT date(str_to_date('2022-12-28T22:28:43.260781049Z','%Y-%m-%d')) as date,
hour(str_to_date('2022-12-28T22:28:43.260781049Z',"%H:%M:%S")) as hour
FROM transaction
And such output:
date
time
'2022-12-28'
NULL
How to get time as well?
You can directly use a CAST on your string value to TIMESTAMP, then extract the date and the time with the hononimous DATE and TIME MySQL functions.
SELECT DATE(CAST(timestamp_ AS DATETIME)) AS date_,
TIME(CAST(timestamp_ AS DATETIME)) AS time_
FROM transactions;
Check the demo here.
Use timestamp instead of str_to_date:
SELECT hour(timestamp('2022-12-28T22:28:43.260781049Z')) as hour

unusual result in Mysql Date Comparison

I have a datetime datatype in my table,
`DateAdded` datetime(4) DEFAULT NULL,
I have a record in my database with DateAdded = 2017-09-11 17:02:48.6531 value, ( it's ID = 16452994 ).
When I want to get it with following query return NULL
select `ID`,`DateAdded` from `Add` where `DateAdded` <= FROM_UNIXTIME(('1505071799' +86400 ), '%Y-%m-%d %h:%i:%s') and ID =16452994 ;
FYI : FROM_UNIXTIME(('1505071799' +86400 ), '%Y-%m-%d %h:%i:%s') = 2017-09-11 23:59:59
It's strange that 2017-09-11 17:02:48.6531 <= 2017-09-11 23:59:59 return false
but when I try the following query I'll get my desire result.
select `ID`,`DateAdded` from `Add` where `DateAdded` <= FROM_UNIXTIME(('1505071799' +86400 +1 ), '%Y-%m-%d %h:%i:%s') and ID =1645299;
I want to know why this is happening and how can I resolve this problem?
FROM_UNIXTIME(unix_timestamp), FROM_UNIXTIME(unix_timestamp,format)
Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context. The value is expressed in the current time zone. unix_timestamp is an internal timestamp value such as is produced by the UNIX_TIMESTAMP() function.
If format is given, the result is formatted according to the format string, which is used the same way as listed in the entry for the DATE_FORMAT() function.
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime

SQL Where clause with VARCHAR date

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')

Most efficient way of flooring todays date

This seems like overkill but is the only way I have been able to floor todays datetime to 00:00:00.000 at database level:
select CAST(FLOOR(CAST(CURRENT_TIMESTAMP AS float)) AS DATETIME)
I have tried using:
select FLOOR(getdate())
But get the following message:
Implicit conversion from data type datetime to float is not allowed. Use the CONVERT function to run this query.
Can anyone recommend another way of doing this?
Since you are using SQL Server 2008 you could make use of the date data type.
declare #Today date
set #Today = getdate()
select #Today
Or without the variable.
select cast(getdate() as date)
If you need to have the value as a datetime just cast it back to a datetime.
select cast(cast(getdate() as date) as datetime)
There are a lot of ways of doing this i have seen the floor one before. Here are a few more.
select cast(cast(CURRENT_TIMESTAMP as date) as datetime)
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SELECT CAST(CAST(CURRENT_TIMESTAMP - 0.50000004 AS int) AS datetime)
I normaly do the Cast to date version.

subtract 2 datetime in mysql ( one in 24 hours format and one in am/pm format )

I'm trying to create a query using mysql.
select ID,NCOde,ifnull(EndTime,now())-starttime from xxx where starttime between
'2012-05-09 00:00:00' and '2012-05-09 23:59:59'
the problem is ifnull(EndTime,now()) return datetime in 24 hours format, while the starttime using am/pm format.
I've tried using DATE_FORMAT(starttime, '%m-%d-%Y %T'), but it seems that the operation changed the datetime type to other type.
Any advice?
Use STR_TO_DATE() to convert your starttime string to a MySQL DATETIME:
STR_TO_DATE(starttime, '%m-%d-%Y %r')
and then use TIMEDIFF() to subtract two times:
select ID,NCOde,
TIMEDIFF(ifnull(EndTime,now()), STR_TO_DATE(starttime, '%m-%d-%Y %r'))
from xxx
where STR_TO_DATE(starttime,'%m-%d-%Y %r')
between '2012-05-09 00:00:00' and '2012-05-09 23:59:59'
You should probably consider changing the data type of the starttime column to DATETIME or TIMESTAMP. Note also that this assumes EndTime is already of such a data type, or else you will also have to perform a similar conversion with it too.
Use the DATE_SUB() function.
Plus what eggyal said.