select milliseconds passed between datetime and now(3) - mysql

I am looking for a way to extract difference in milliseconds between two date. One date is stored, and is a date of a particular event. Second date is the result of now(3) statement. I need to store also milliseconds.
Until now, I've discovered timediff function. But this returns something like HH:ii:ss.mm. I need, in SQL to convert this result in milliseconds.
mysql> select timediff(now(3), updated_at) from events;
+------------------------------+
| timediff(now(3), updated_at) |
+------------------------------+
| 00:42:22.240 |
+------------------------------+
1 row in set (0,01 sec)

MySQL only supports microsecond for a higher resolution, but you can achieve it by converting microsecond to millisecond manually:
SELECT TIMESTAMPDIFF(MICROSECOND, now(3), updated_at) / 1000 AS diff_in_ms FROM events;

Related

Select a record based on timestamp

I have a table that has a column row filled with a Javascript's, Date.now() function.
The column name is update_time, and its sample value is 1571152209099.
How can I make a Select for all rows that have todays date (taking into account only year, month and a day)?
I have tried something like this, but it get's me nowhere.
Select *
from program_end
where workout_rate between 0 and 1
AND FROM_UNIXTIME(update_time, '%YYYY-%MM-%DD') = CURDATE()
I also tried changing the time format:
Select *
from program_end
where FROM_UNIXTIME(update_time, '%Y-%m-%d') = CURDATE()
But no result whatsoever.
Any insight is appreciated.
For insight, consider:
SELECT '1970-01-01' + INTERVAL ( 1571152209099 /1000) SECOND
returns:
_dt
--------------------------
2019-10-15 15:10:09.099000
We recognize that the 1571152209099 value from JavaScipt Date.now() is integer milliseconds from the beginning of the era (Jan 1, 1970 midnight UTC).
Also consider:
SELECT TIMESTAMPDIFF(SECOND,'1970-01-01 00:00','2019-10-15 00:00')*1000 AS _dt_1
, TIMESTAMPDIFF(SECOND,'1970-01-01 00:00','2019-10-16 00:00')*1000 AS _dt_2
returns:
_dt_1 _dt_2
------------- --------------
1571097600000 1571184000000
The TIMESTAMPDIFF function is returning a difference in seconds; we multiply by 1000 to get milliseconds.
We recognize that any JavaScript Date.now() milliseconds value that is greater than or equal to _dt_1 and is less than _dt_2 occurs sometime "on" the date '2109-10-15'
So, given update_time is milliseconds since the beginning of the era...
In a query, I would compare the bare update_time column to two literal values:
WHERE update_time >= 1571097600000
AND update_time < 1571184000000
Referencing the bare column has the advantage that MySQL can make use of an efficient range scan operation, with a suitable index available.
To derive those millisecond values from a given date value, we can do a calculation in an expression, like this:
WHERE update_time >= TIMESTAMPDIFF(SECOND,'1970-01-01', '2019-10-15' )*1000
AND update_time < TIMESTAMPDIFF(SECOND,'1970-01-01', '2019-10-15' + INTERVAL 1 DAY)*1000
^^^^^^^^^^
Those expressions on the right side get evaluated just one time at the start of the statement execution.
Note that if we wrap update_time in a function, then that function has to be evaluated for every value of update_time, for every row in the table (that isn't filtered out by some other predicate.)
If you don't have dates in the future, you can simply do:
WHERE update_time >= UNIX_TIMESTAMP(CURDATE())
This will happily use an existing index on update_time.
If you have dates in the future that you need to exclude from the resultset, then:
WHERE
update_time >= UNIX_TIMESTAMP(CURDATE())
AND update_time < UNIX_TIMESTAMP(CURDATE() + INTERVAL 1 DAY)
Javascript's Date.now is giving you milliseconds, whereas MySQL's FROM_UNIXTIME expects seconds.
Unable to understand the epoch timestamp in milliseconds, FROM_UNIXTIME is returning NULL, which is of course failing to match the current date.
mysql> SELECT FROM_UNIXTIME(1571152209099);
+------------------------------+
| FROM_UNIXTIME(1571152209099) |
+------------------------------+
| NULL | -- THIS IS YOUR PROBLEM
+------------------------------+
1 row in set (0.00 sec)
mysql> SELECT FROM_UNIXTIME(1571152209099/1000);
+-----------------------------------+
| FROM_UNIXTIME(1571152209099/1000) |
+-----------------------------------+
| 2019-10-15 10:10:09.0990 |
+-----------------------------------+
1 row in set (0.00 sec)
Try this:
FROM_UNIXTIME(FLOOR(update_time/1000), format...)

Possibly Mysql 5.6.20 bug. Date - now()?

date_newOrd, now(), date_newOrd-now() AS `time`
this is my query. date_newOrd is type date. I try to calculate the time remaining for next arrival of order. I better show you the screenshot:
the result is doesn't make any sense. What am i supposed to do>
You cannot subtract dates like that:
mysql> select '2015-06-01 18:20:03' - now();
+-------------------------------+
| '2015-06-01 18:20:03' - now() |
+-------------------------------+
| -20150602073525 |
+-------------------------------+
While that may look (vaguely) like a date, it's really an integer, and can't be used for further date math without extra processing.
You have to use datediff() or timediff():
mysql> select timediff('2015-06-01 18:20:03', now()) as td, datediff('2015-06-01 18:20:03', now()) as dd;
+-----------+------+
| td | dd |
+-----------+------+
| -13:37:47 | -1 |
+-----------+------+
note that datediff deals only with DATES, and timediff deals with datetime values.
When you do a subtraction, MySQL is going to evaluate NOW() in a numeric context, it returns a numeric value.
SELECT NOW()+0
20150602135210.000000
So, your statement is doing a subtraction of numbers, not doing a DATE calculation.
Some possibilities:
You could convert the datetime values into unix_timestamp values, (UNIX_TIMESTMAP() function) and then do a subtraction of those to get a difference in integer seconds.
The DATEDIFF() function would get you a difference in integer days. (That operates only on the date portion, it ignores the time... so that probably doesn't give you the resolution you are looking for.)
The TIMESTAMPDIFF() and TIMEDIFF() functions are also available. (The TIMEDIFF functions returns a TIME datatype value; the maximum value of that datatype is 838:59:59, so that's limited to just under 35 days elapsed).
For example:
SELECT UNIX_TIMESTAMP('2015-06-03') - UNIX_TIMESTAMP(NOW()) AS secs
secs
-------
35856

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.

MySQL TIMEDIFF(DATE, DATETIME)

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)

Filter by current date in MySQL

How to pass the current date to a query in mysql like such query:
select from Dailytimesheet dailytimesheet where dailytimesheet.TrackingDate="2010-05-03"
In MySQL, you can use CURRENT_DATE to get the current date.
mysql> select CURRENT_DATE;
+--------------+
| CURRENT_DATE |
+--------------+
| 2010-05-03 |
+--------------+
1 row in set (0.08 sec)
Using NOW() works as well, but gets you the current date and time as a timestamp value. You can truncate it like DATE(NOW()), but CURRENT_DATE avoids the function call.
you can use the NOW() function within your SQL query to get the current timestamp.