Adding Time to MYSQL DATETIME fields? - mysql

I have a system where tablets perform tasks and report back with what tasks have been completed and when. One of the tablets has come out of sync and the time is 2 days, 3 hours, 31 mins and 31 secs behind, which is messing up my reporting.
Is there an easy way to add the missing time to the fields with a query?
I can identify which fields need to be altered as they are all tied to a single job, so can add WHERE job_id = 998 to the end.
I have had a look around, and can't really make sense of answers provided, and can't afford to mess up and insert the incorrect times.
Just for clarification, I basically have an event that the tablet believes happened at '2015-12-01 07:57:30' but actually happened at '2015-12-03 11:29:01'. I worked that one out manually, but I have over 100 rows that need updating. Something like: UPDATE job_logs SET entry_time = <CURRENT FIELD DATE> ADD <OUT OF SYNC TIME> WHERE job_id = 998;
Any answers are appreciated, additional detail would be preferred as I'm still learning & would like to understand how the solution works...
Thanks in advance!

You can use MySQL DATE_ADD() function, check this below given SELECT query with your <CURRENT FIELD DATE> field
SELECT <CURRENT FIELD DATE>,DATE_ADD(<CURRENT FIELD DATE>, INTERVAL '2 3:31:31' DAY_SECOND)
FROM job_logs
WHERE job_id = 998;
then you can use same in your UPDATE query as
UPDATE job_logs
SET entry_time = DATE_ADD(<CURRENT FIELD DATE>, INTERVAL '2 3:31:31' DAY_SECOND)
WHERE job_id = 998;
I hope this works...

there is no issue with adding date or time in a datetime filed in mysql
UPDATE job_logs SET entry_time = ADDTIME(entry_time , '1:2:3') WHERE job_id = 998
this will update your entry_time to 1 hour 2 min and 3 sec to existing entry_time.

Related

How to add extra 5 minutes in mysql using query

I'm new for mysql, Already value in time field, I want to update extra 5 minutes in time field using query. I tried so many things but not working.
Here my query:
UPDATE STUDENT SET START_TIME = ADDTIME(START_TIME, 500) WHERE ID = 1;
Above query working but one issue is there that is, If my field having 23:55:00.
I want result after executing query 00:00:00 but it updates 24:00:00.
Anyone help me!
Thanks in advance!!
This is bit tricky, because you only have the time, and you want it to wrap around to 0 after hitting 24 hours. My approach is to extract the number of seconds from START_DATE, add 5 minutes, then take the mod of this by 24 hours to wrap around to zero if it exceeds one day's worth of seconds.
UPDATE STUDENT
SET START_TIME = CAST(STR_TO_DATE(CAST(MOD((TIME_TO_SEC(START_TIME) + 300), 86400) AS CHAR(5)), '%s') AS TIME)
WHERE ID = 1
In the demo below, you can see the logic in action which correctly converts 23:55:00 with five minutes added to become 00:00:00.
SQLFiddle
However, the easiest solution in your case might be to just use a DATETIME and ignore the date component. Then the time should wrap automatically to a new day.
select addtime('23:55:00', '00:06:00');
output - 24:01:00 (Ideally it is right, because time datatype represents only time, if it converts to 00:01:00 then time component looses 24hr, which is wrong)
select addtime('2016-09-01 23:55:00', '00:06:00');
output - 2016-09-02 00:01:00 (In this case, 24hr gets added in date so time component is represented as 00:01:00)
If the requirement is to get it as 00:01:00 then here is the workaround -
SELECT TIME((ADDTIME(TIME('23:59:59'), TIME('02:00:00')))%(TIME('24:00:00')));
reference -
ADDTIME() return 24 hour time

get range between two timestamp

I like to get the total hours in between two timestamp.
Take a look at my code
$sql="UPDATE timekeeping SET end= timestamp(NOW()),totalrange = ((end- begin) - 1)
WHERE end IS NULL and fullname = '$whoareyou[fullname]'";
but in this code "totalhours = ((end- begin) - 1)" is wrong i feel it :)
I want this to show something like this
2014-05-07 02:00:38.000000 - 2014-05-07 06:00:38.000000 = 4
and something like this
2014-05-07 02:00:38.000000 - 2014-05-07 06:30:38.000000 = 4.30
but i do not know where or what to do.
Please help anyone. I have done my part in researching and found no suitable answer which I can understand since this was my first time to use php.
The following SQL query should do the trick:
SELECT TIMESTAMPDIFF(HOUR, '2012-06-06 13:13:55', '2012-06-06 15:20:18');
Replace the second argument with the date they last logged in and the third argument with the date of their current login.
This will return an integer equal to the hours between the first time stamp and the second time stamp.
EDIT: If you wish to get also the minutes, then replace 'HOUR' with 'MINUTE' and do some math to get the decimal value of Hours.Minutes.

How to calculate time difference in MYSQL

I have Rails application which using MYSQL as database. For some condition, I have to delete all the records from table which was stored exactly 2 hours before the current time.
My query is :
DELETE FROM TABLE_NAME WHERE (NOW() - created_at) > 7200;
Here create_at is datetime column type. Storing the value in the format "2012-12-04 06:39:44"
My problem is, the above query fetch the records even though the record created time is just 40 to 50 minutes and got deleted. The only problem is the record got delete after it reach 40 to 50 minx from it create time.
Can any one please correct my query. I want the MySQL solution. Please help me
You probably need this if you want to delete records created exactly 2 hours ago:
DELETE FROM TABLE_NAME WHERE created_at = NOW() - INTERVAL 2 HOUR
or this, that will delete all records created more than 2 hours ago:
DELETE FROM TABLE_NAME WHERE created_at < NOW() - INTERVAL 2 HOUR
Try this ::
DELETE FROM TABLE_NAME WHERE TIMEDIFF(NOW(),created_at) < '02:00:00';
Try:
DELETE FROM TABLE_NAME WHERE created_at<DATE_SUB(NOW(),INTERVAL 2 HOUR)
This query will delete everything created MORE THAN 2 hours ago. Putting an equal sign would mean EXACTLY 2 hours ago (in second). Of course you can format date to consider only minutes, but that would slow down the query.
If created_at is indexed (and I think it should be) don't perform any functions on it so it can use index to perform delete faster.
I understand you want to delete all records created within a time lapse. So, you shouldn't apply a "greater than" operator to the subtract operation. Instead you should try to specify an appropriated time frame.
You could also take a look to the timediff function http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff
Sorry I'm not able to post the right statement for you, since I don't have a mysql server at hand.

Trying to calc diff of now and last time stamp and update timestamp

I am trying to do some basic estimating of how long users spend on a site. I have a simple polling script in javascript that hearbeats out to a php script. I'm trying to do the following in one sql statement:
calculate the difference between now and the last updated_on field (which is a datetime field ) and add it to the current active_time field (which is just an integer)
Then update the updated_on to reflect that the record has been updated
This is the sql I'm trying to use;
UPDATE login_log
SET active_time = active_time + ( SELECT TIME_TO_SEC( TIMEDIFF( NOW(), updated_on ) ) ),
updated_on = NOW()
WHERE user_id = ? && session_id = ? AND status = 'active'
Question 1 - I'm assuming I can update updated_on and still use it to calc the difference and not have a race condition, but can someone confirm or tell me that doesn't work?
Question 2 - I must be doing something else wacky because after abit, the active_time is way off as in it thinkgs it's been going for hours when it's only been 20 minutes. Not really scope of this quesiton, but if anyone sees anything quickly that is wrong, I'd appreciate knowing ....
TIA
This seems like the wrong way to go about this. I would simplify it having two fields, created and updated_on, which I would call last_updated. To calculate the current time on the site you would simply subtract the created value from the current time. Presumably, you want some permanent record as well. That comes from the last_updated field, which is updated each time a request from the user is seen (including your heartbeat). You simply update it with the current time. The difference between created and last_updated becomes your permanent record of the time on site.

How to calculate hours in mysql

My problem is in brief here...
Once a user signed in i stored his login date in the users table. If the user doesn't logged in for 72 hours i need to change his status to inactive.
How can i able to find whether 72 hours is completed or not after the user logged in using My Sql.
Thanks in advance...
I'd recommend using the TIMEDIFF() function, which you can find documented here:
dev.mysql.com timediff doc.
In your case, I'd format my where clause something like this:
WHERE
TIMEDIFF(CURTIME(), LastLoginDate) > '3 0:0:0.0'
or
WHERE
TIMEDIFF(CURTIME(), LastLoginDate) > '72:0:0.0'
I haven't done this specifically, but the base concept should work for you.
Create a CRON routine to run every hour with this query:
UPDATE users
SET status = 'Inactive'
WHERE (SELECT * FROM users WHERE last_login < now() - 259200)
To answer your question more specifically, it is the where clause, when ran, that tells you all the users that haven't logged in for 72 hours.
SELECT * FROM users WHERE last_login < now() - 259200
However, there is no way to set each user to inactive at exactly 72 hours. To get more accurate than the solution provided above, run the query more often.
*Note - insert your columns names where appropriate. Query not tested. 259200 = # of seconds in 72 hours - assumes you store your timestamps seconds (Epoch)
Use DATETIME type to store dates, subtract 72 hours from NOW() using DATE_SUB() and see if the result is larger than the value stored in the database.