MySQL TIMEDIFF(DATE, DATETIME) - mysql

I have two columns in MySQL database.
One is in DATE format like 2014-01-26, another one is in DATETIME format: 2014-01-25 17:19:07.
I need to apply TIMEDIFF(2014-01-26, 2014-01-25 17:19:07) function, but it requires both variables are in DATETIME format. How can I convert 2014-01-26 to 2014-01-26 00:00:00?

You can always cast a Date to a datetime
select timediff(cast(<yourDateColumn> as Datetime), <yourDatetimeColumn>)
But I'm not even really sure that you need to cast (depending on your mysql version), I may misunderstand the doc, but we can read
Prior to MySQL 5.1.18, when DATE values are compared with DATETIME
values, the time portion of the DATETIME value is ignored, or the
comparison could be performed as a string compare. Starting from MySQL
5.1.18, a DATE value is coerced to the DATETIME type by adding the time portion as '00:00:00'. To mimic the old behavior, use the CAST()
function to cause the comparison operands to be treated as previously.
For example:

You can use date_format()
mysql> select
TIMEDIFF(date_format('2014-01-26','%Y-%m-%d %H:%i:%s'), '2014-01-25 17:19:07')
as diff;
+----------+
| diff |
+----------+
| 06:40:53 |
+----------+
1 row in set (0.00 sec)
mysql> select date_format('2014-01-26','%Y-%m-%d %H:%i:%s') as date;
+---------------------+
| date |
+---------------------+
| 2014-01-26 00:00:00 |
+---------------------+
1 row in set (0.00 sec)

Related

Error: Update Varchar values to Datetime in MySQL

DB DETAIL Table name(KK)-
id name date(varchar(50))
1 Ayush 2020-04-19T18:56:09.774Z
I am using this query to convert -
update KK set date=DATE_FORMAT(STR_TO_DATE( KK.date, '%Y-%m-%dT%H:%i:%s' ), '%Y-%m-%d %T') where id=1;
Getting this error
Error Code: 1292. Truncated incorrect datetime value: '2020-04-19T18:56:09.774Z'
Your current date string has .774Z following the seconds, but your STR_TO_DATE() format string doesn't account for it. So it's warning you that there are extra characters at the end of the string that weren't parsed.
If you use '%Y-%m-%dT%H:%i:%s.%fZ' the warning stops.
The times have two parts your format is missing: milliseconds, the .774 part, and the "zulu" time zone Z.
select STR_TO_DATE('2020-04-19T18:56:09.774Z', '%Y-%m-%dT%H:%i:%s.%fZ');
However, since you're truncating them anyway, I'd use the less restrictive format and just ignore the warning.
Since the string is already in ISO 8601 format, you can skip the str_to_date.
mysql> select DATE_FORMAT('2020-04-19T18:56:09.774Z', '%Y-%m-%d %T');
+--------------------------------------------------------+
| DATE_FORMAT('2020-04-19T18:56:09.774Z', '%Y-%m-%d %T') |
+--------------------------------------------------------+
| 2020-04-19 18:56:09 |
+--------------------------------------------------------+
1 row in set, 1 warning (0.00 sec)
The MySQL warning is because it doesn't seem to understand that Z is a valid time zone designator.
Note that this will account for a time zone. This may or may not be what you want.
-- date_format will display in the current time zone.
-- I'm in -07:00, so a +00:00 (UTC) date is displayed -7 hours.
mysql> select DATE_FORMAT('2020-04-19T18:56:09.777+00:00', '%Y-%m-%d %T');
+-------------------------------------------------------------+
| DATE_FORMAT('2020-04-19T18:56:09.777+00:00', '%Y-%m-%d %T') |
+-------------------------------------------------------------+
| 2020-04-19 11:56:09 |
+-------------------------------------------------------------+
1 row in set (0.00 sec)
And, finally, consider altering that column to be a datetime type. Then everything is stored in UTC and these conversion problems go away.

Mysql Timestamp difference results

I have a table with a TIMESTAMP field (lastHonored).
I ran this query:
SELECT NOW(), lastHonored,
TIMESTAMPDIFF(SECOND, lastHonored, NOW()), NOW()-lastHonored
FROM db.table
I get the result:
NOW() | lastHonored | DIFF | SUBTRACT
2014-10-27 14:07:22 | 2014-10-26 19:49:51 | 65851 | 945771
Where DIFF is the result of the TIMESTAMPDIFF function, and SUBTRACT is the result of the NOW()-lastHonored expresssion.
DIFF looks right, but can anyone tell me what NOW()-lastHonored calculates? It is not the right order of magnitude, and I'm stumped.
One would think that NOW() returns a datetime or similar type. But no. For some historical reason, NOW() returns either a number or a string. To quote the documentation:
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS'
or YYYYMMDDHHMMSS format, depending on whether the function is used in
a string or numeric context. The value is expressed in the current
time zone.
That means that NOW() gets converted to a value based on its context. The - suggests a numeric context, so NOW() is a number whose digits are YYYYMMDDHHMMSS. My guess is that lastHonored gets similarly converted, so the result is the difference between two numbers.
You can see why by running:
SELECT CAST(NOW() AS UNSIGNED), CAST('2014-10-26 19:49:51' AS UNSIGNED);
By doing simple subtraction, MySQL is turning both values into numbers. NOW() the DATETIME becomes 20141027141923, but 2014-10-26 19:49:51 the STRING becomes 2014.
If you first cast the date to a DATETIME it gives you results more along the lines of what you expect:
SELECT CAST(NOW() AS UNSIGNED), CAST(CAST('2014-10-26 19:49:51' AS DATETIME) AS UNSIGNED);
You can't subtract dates like you are with NOW()-lastHonored. Dates/datetimes are not directly "subtractable":
MariaDB [test]> select '2014-10-27 08:18:00' - '2014-10-27 08:17:00';
+-----------------------------------------------+
| '2014-10-27 08:18:00' - '2014-10-27 08:17:00' |
+-----------------------------------------------+
| 0 |
+-----------------------------------------------+
1 row in set, 2 warnings (0.00 sec)
MariaDB [test]> show warnings;
+---------+------+---------------------------------------------------------+
| Level | Code | Message |
+---------+------+---------------------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: '2014-10-27 08:18:00' |
| Warning | 1292 | Truncated incorrect DOUBLE value: '2014-10-27 08:17:00' |
+---------+------+---------------------------------------------------------+
2 rows in set (0.00 sec)
Note the warnings. You'll get results, but they almost always be totally useless/incorrect results, because MySQL is casting the date values as doubles.
They do different things, substraction does not take into account that you are dealing with times.
If you do:
SELECT NOW(), lastHonored,
TIMESTAMPDIFF(SECOND, lastHonored, NOW()) THE_DIFF, NOW()-lastHonored THE_SUBSTRACTION,
NOW()+0 NOW_NUMBER_REPRESNTATION,
lastHonored+0 lastHonored_NUMBER_REPRESENTATION
FROM db.table
You will see the numeric difference is represented with the substraction and the time differente with TIMESTAMPDIFF.

Converting epoch number to human readable date in mysql

I have a epoch number say 1389422614485.
The datatype for the value storing this value is varchar.
I want to convert its value to human readable time.
How can we do it?
Any example for this conversion?
Your epoch value 1389422614485 seems like having the millisecond precision. So you need to use some mysql mathematical functions along with from_unixtime() for generating human readable format.
mysql> select from_unixtime(floor(1389422614485/1000));
+------------------------------------------+
| from_unixtime(floor(1389422614485/1000)) |
+------------------------------------------+
| 2014-01-11 12:13:34 |
+------------------------------------------+
Update July 2020: As of MySQL 8.0, the floor function is no longer necessary when working with milliseconds:
mysql> select from_unixtime(1594838230234/1000);
+------------------------------------------+
| from_unixtime(1594838230234/1000) |
+------------------------------------------+
| 2020-07-15 18:37:10.2340 |
+------------------------------------------+
Take a look at from-unixtime
mysql> SELECT FROM_UNIXTIME(1196440219);
-> '2007-11-30 10:30:19'
You can use from_unixtime() as follows:
SELECT from_unixtime(1388618430);
which returns 2014-01-02 00:20:30
This wil work for both +positive and -negative epoch, in-case for old birth dates, and also if you want to specify date format
select
date_format(DATE_ADD(from_unixtime(0), interval '1389422614485'/1000 second), '%Y-%m-%d %H:%i:%s') as my_new_date;

How to convert human date to unix timestamp in Mysql?

I have a table with a date field, having human date in it like: '2008-01-08 19:23:32'
Now i have to copy this field plus some other fields of the same table to another table, but date needs to be in unix timestamp.
Is there any function in mysql which converts human date to unix timestamp inside query itself?
mysql> select unix_timestamp('2008-01-08 19:23:32');
+---------------------------------------+
| unix_timestamp('2008-01-08 19:23:32') |
+---------------------------------------+
| 1199849012 |
+---------------------------------------+
1 row in set (0.04 sec)
found here: http://www.epochconverter.com/
UNIX_TIMESTAMP() Should do the trick!
From MySQL Docs:
If called with no argument, returns a Unix timestamp (seconds since
'1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP()
is called with a date argument, it returns the value of the argument
as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string,
a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD or
YYYYMMDD. The server interprets date as a value in the current time
zone and converts it to an internal value in UTC.
mysql> SELECT UNIX_TIMESTAMP();
-> 1196440210
mysql> SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');
-> 1196440219
SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');
Yes.
SELECT UNIX_TIMESTAMP(column) FROM TABLE
Query:
SELECT UNIX_TIMESTAMP(TIMESTAMP(`opened`)) as timestamp_date, `opened` as datetime_type FROM `myterminal`
Outputs:
| timestamp_date | datetime_type
|------------------- |---------------------
| 1536602012 | 2018-09-10 14:53:32
| 1536603854 | 2018-09-10 15:24:14

how to change default date format when creating table in MYSQL

how to change default date format when creating table in MYSQL
You can't change the default format for a date during the table definition stage. (It must always obey the DATETIME, DATE or TIMESTAMP formats.) As the manual puts it:
Although MySQL tries to interpret
values in several formats, dates
always must 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').
See the date and time reference docs for more info.
As such, you'll have to use the DATE_FORMAT() function at the point of output to achieve this goal.
You may want to use the STR_TO_DATE() and DATE_FORMAT() functions to communicate with MySQL using different date formats.
Example using STR_TO_DATE():
SELECT STR_TO_DATE('15-Dec-09 1:00:00 PM', '%d-%b-%y %h:%i:%S %p') AS date;
+---------------------+
| date |
+---------------------+
| 2009-12-15 13:00:00 |
+---------------------+
1 row in set (0.07 sec)
Example using DATE_FORMAT():
SELECT DATE_FORMAT('2009-12-15 13:00:00', '%d-%b-%y %h:%i:%S %p') AS date;
+-----------------------+
| date |
+-----------------------+
| 15-Dec-09 01:00:00 PM |
+-----------------------+
1 row in set (0.00 sec)