Mysql Time Arithmetic - Time only - mysql

This should be so easy... but is driving me mad.
UPDATE time SET time = (time - interval 130 minute) WHERE stuff=whatever;
Time is a time column only, i.e. 09:00:00.

Assuming that you would like to subtract 130 minutes from the current time, you can use addtime, like this:
UPDATE time SET time = addtime(time, '-02:10') where stuff=whatever
130 minutes is 2 hours and 10 minutes, hence the -02:10 constant.
Here is a quick demo on sqlfiddle.

Change - to , and it will work. The correct Query is:
UPDATE time SET time = (time, interval 130 minute) where stuff=whatever

If time is a datetime or a timestmap, you must use a date_sub funktion
SELECT date_sub(time, interval 130 minute) FROM ....
Otherwise you can also convert your time with UNIX_TIMESTAMP, sub it and convert with FROM_TIMESTAMP into a mysql timestamp back

There is a DATE_SUB method that works like the DATE_ADD method you are looking for.
DATE_SUB(NOW(),INTERVAL 130 MINUTE)
Check this link for more information:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-sub

Related

SQL - Calculate 30 days ago and delete

I am trying to clear a MySQL database of entries in a table that are older than 30 days.
I think I am correct by doing it like this...
DELETE from wp_rg_lead_detail WHERE date_created < '11/05/18'
But is there a way I can get the SQL statement to calculate 30 days ago automatically? That way I could set a cronjob up and have it run everyday without me having to manually enter the date.
Use curdate() to get the current date and date_add() to subtract 30 days from it.
date_add(curdate(), INTERVAL -30 DAY);
Use date_add and sysdate functions to calculate date dynamically.
Date_add(sysdate(), interval -30 days)

How sum 24 hours to time mysql?

I've got a column time type in mysql, i want to add 24 hours to this hour, i try with code below:
SELECT SUBSTRING(CAST(DATE_ADD(STR_TO_DATE('23:00', '%k:%i'), INTERVAL (TIME_TO_SEC('24:00') / 60) MINUTE) AS CHAR(8)), 1,5)
I need to return 23:00 again (because i add 24 hours but that 23:00 is of the next day) but this code return me 47:00.
Some help?
I think you're looking for ADDTIME
SELECT ADDTIME(‘23:00’,’24:00’)
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_addtime
You need to first convert the column value to a datetime, add the hours, and then convert the result back to time:
select cast(date_add(cast(time_column as datetime), interval 24 hour ) as time)
from yourtable;
Example:
select cast(date_add(cast(cast('23:00' as time) as datetime), interval 24 hour ) as time)
The TIME type allows you to store up to (but not including) 839 hours (positive and negative). That's great if you need to store duration, but not so much if you want to store time of day. If you want the latter you should consider the DATETIME type instead.

How do I increment a value in MySQL to a certain time in the future?

I am trying to update a DATETIME field in a table. What I want for it is to always have three hours before it expires.
My current code is:
UPDATE mindcore_sessions
SET session_time = DATE_ADD(session_time, INTERVAL 3 HOUR)
WHERE session_id = '$sessionId';
An example value would be: 2013-02-11 00:00:00. If I run this query, it will change to: 2013-02-11 03:00:00. Which is correct. But, if it is run again, it changes to 2013-02-11 06:00:00 and so on.
What I want for it is to always be only three hours ahead. This is hard to explain, but I just want it to stay the same if it is run again. And if it is run again 1 minute later, I want it to increment by just one minute.
Sorry if the question is verbose, but I am utterly confused (and it is late!).
Thanks :)
Instead of adding three(3) hours to the last session_time, add three(3) hours to NOW():
update mindcore_sessions
set session_time = DATE_ADD(NOW(), INTERVAL 3 HOUR)
where session_id = '$sessionId';`
Add your interval to NOW() instead of adding to the current value:
UPDATE mindcore_sessions SET session_time = DATE_ADD(NOW(), INTERVAL 3 HOUR) WHERE session_id = '$sessionId';
There is no way in mysql to know if the same query was executed before.
The only possible solution would be to save the original value in an extra column, and use this column to check if the value was changed in the past.
If you want the value to be ahead 3 hours from now, you can simply do this:
DATE_ADD(NOW(), INTERVAL 3 HOUR)

MYSQL Date Time Round To Nearest Hour

I have a date time field in a MySQL database and wish to output the result to the nearest hour.
e.g. 2012-04-01 00:00:01 should read 2012-04-01 00:00:00
Update: I think https://stackoverflow.com/a/21330407/480943 is a better answer.
You can do it with some date arithmetic:
SELECT some_columns,
DATE_ADD(
DATE_FORMAT(the_date, "%Y-%m-%d %H:00:00"),
INTERVAL IF(MINUTE(the_date) < 30, 0, 1) HOUR
) AS the_rounded_date
FROM your_table
Explanations:
DATE_FORMAT: DATE_FORMAT(the_date, "%Y-%m-%d %H:00:00") returns the date truncated down to the nearest hour (sets the minute and second parts to zero).
MINUTE: MINUTE(the_date) gets the minute value of the date.
IF: This is a conditional; if the value in parameter 1 is true, then it returns parameter 2, otherwise it returns parameter 3. So IF(MINUTE(the_date) < 30, 0, 1) means "If the minute value is less than 30, return 0, otherwise return 1". This is what we're going to use to round -- it's the number of hours to add back on.
DATE_ADD: This adds the number of hours for the round into the result.
Half of the hour is a 30 minutes. Simply add 30 minutes to timestamp and truncate minutes and seconds.
SELECT DATE_FORMAT(DATE_ADD(timestamp_column, INTERVAL 30 MINUTE),'%Y-%m-%d %H:00:00') FROM table
soul's first solution truncates instead of rounding and the second solution doesn't work with Daylight Savings cases such as:
select FROM_UNIXTIME(UNIX_TIMESTAMP('2012-03-11 2:14:00') - MOD(UNIX_TIMESTAMP('2012-03-11 2:14:00'),300));
Here is an alternate method (1):
DATE_ADD(
tick,
INTERVAL (IF((MINUTE(tick)*60)+SECOND(tick) < 1800, 0, 3600) - (MINUTE(tick)*60)+SECOND(tick)) SECOND
)
If you don't need to worry about seconds you can simplify it like this (2):
DATE_ADD(
tick,
INTERVAL (IF(MINUTE(tick) < 30, 0, 60) - MINUTE(tick)) MINUTE
)
Or if you prefer to truncate instead of round, here is simpler version of soul's method (3):
DATE_SUB(tick, INTERVAL MINUTE(tick)*60+SECOND(tick) SECOND)
EDIT: I profiled some of these queries on my local machine and found that for 100,000 rows the average times were as follows:
soul's UNIXTIME method: 0.0423 ms (fast, but doesn't work with DST)
My method 3: 0.1255 ms
My method 2: 0.1289 ms
Ben Lee's DATE_FORMAT method: 0.1495 ms
My method 1: 0.1506 ms
From How to round a DateTime in MySQL?:
It's a little nasty when you do it with datetime data types; a nice candidate for a stored function.
DATE_SUB(DATE_SUB(time, INTERVAL MOD(MINUTE(time),5) MINUTE ),
INTERVAL SECOND(time) SECOND)
It's easier when you use UNIXTIME timestamps but that's limited to a 1970 - 2038 date range.
FROM_UNIXTIME(UNIX_TIMESTAMP(time) - MOD(UNIX_TIMESTAMP(time),300))
Good luck.
To round down to the current hour, select:
FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(column_name) / 3600) * 3600).
The value is expressed in the current time zone doc
This will return the next hour, that is '2012-01-02 18:02:30' will be converted into '2012-01-02 19:00:00'
TIMESTAMPADD(HOUR,
TIMESTAMPDIFF(HOUR,CURDATE(),timestamp_column_name),
CURDATE())
Instead of CURDATE() you can use an arbitrary date, for example '2000-01-01'
Not sure if there could be problems using CURDATE() if the system date changes between the two calls to the function, don't know if Mysql would call both at the same time.
to get the nearest hour would be:
TIMESTAMPADD(MINUTE,
ROUND(TIMESTAMPDIFF(MINUTE,CURDATE(),timestamp_column_name)/60)*60,
CURDATE())
changing 60 by 15 would get the nearest 15 minutes interval, using SECOND you can get the nearest desired second interval, etc.
To get the previous hour use TRUNCATE() or FLOOR() instead of ROUND().
Hope this helps.
If you need to round just time to next hour you may use this:
SELECT TIME_FORMAT(
ADDTIME(
TIMEDIFF('16:15', '10:00'), '00:59:00'
),
'%H:00:00'
)
I think this is the best way, since it also will use the least amount of resources-
date_add(date(date_completed), interval hour(date_completed) hour) as date_hr

mySQL SELECT timestamp(now()-3000);

I'm trying to make a query which brings back results based on a timestamp, say an interval of 30 minutes.
So what I figured out is that I can
SELECT * FROM x WHERE ts BETWEEN timestamp(now()-3000) AND timestamp(now())
So this will query everything from x with timestamps in column ts within the last 30 minutes.
However, this only works after now() is past the yyyy-mm-dd HH:30:00 mark because anytime before it will result in NULL... this is rather cumbersome and I don't understand why it won't just subtract the friggin minutes from the hour!
Please help me out! I couldn't find any other method of doing a query within the last 30 minutes, that is what I'm trying to achieve.
Best regards,
John
SELECT * FROM x WHERE ts BETWEEN timestamp(DATE_SUB(NOW(), INTERVAL 30 MINUTE)) AND timestamp(NOW())
SELECT * FROM x WHERE ts BETWEEN NOW() - INTERVAL 30 MINUTE AND NOW();
SELECT * FROM x
WHERE ts BETWEEN TIMESTAMPADD(MINUTE, -30, NOW()) AND NOW();
First of all you need to realize that timestamp() returns a unix timestamp in seconds. 3000 seconds is not 30 minutes, it should be 1800 seconds. try that
For me, what worked is following query
select * from x where (now() - ts) < 1800000
1800000 is 30 minutes, because 60000 ms is 1 minute
You'll have to use DATE_ADD() and DATE_SUB() operators for dates. Take a look at the documentation: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
SELECT * FROM (`yourdb`) WHERE `timestamp` BETWEEN NOW() - INTERVAL 30 MINUTE AND NOW();