MySQL - Truncating Date/Time and Subtracting from Each Other - mysql

I have the following query which subtracts the original purchase time from the expires time to come up with a number of days:
select date(expires_dtime) - date(original_purchase_dtime)
from sl_player_subscription
where player_uuid = '9c61411c-54b4-45bd-8d07-264b1c2e4249'
player_uuid that = '9c61411c-54b4-45bd-8d07-264b1c2e4249' has an original purchase time of 2013-03-06 11:36:46 and an expire time of 2013-04-05 12:36:46.
I want the output to read "30" which is the number of days between the purchase time and the expire time, but instead the output is 99. Any suggestions?

You can use DATEDIFF:
SELECT DATEDIFF('2013-04-05 12:36:46', '2013-03-06 11:36:46')
Result
30
Using your columns:
SELECT DATEDIFF(expires_dtime, original_purchase_dtime)
See the demo
DATEDIFF() returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.
Documentation: Date and Time functions

Related

day difference between today's date and a specified date in SQL

How to find the day difference between today's date and a specified date in SQL. The specified date column(P.SubscrpEndDate__c) is in Date time format(12/1/2014 12:00 Am). I have used the below query but it do not works
DATEDIFF(day,GETDATE(), P.SubscrpEndDate__c) AS 'SubscriptionDueDate'
In MySQL, DATEDIFF function, takes only two arguments: end date and start date:
DATEDIFF(NOW(), P.SubscrpEndDate__c) AS 'SubscriptionDueDate'
According to the manual:
DATEDIFF(expr1, expr2) returns expr1 − expr2 expressed as a value in days from
one date to the other.
Also, to get the current date and time you have to use NOW() instead of GETDATE.
It should work in SQL Server. I assume date column(SubscrpEndDate__c) in your table would contain lower values than current date, so simply you can use query below. I've just swapped second & third parameters to get positive difference in days. You can also use ABS() function to ignore negative difference.
SELECT DATEDIFF(day,P.SubscrpEndDate__c,GETDATE() ) AS 'SubscriptionDueDate'
This would work, kindly check
SELECT DATEDIFF(NOW(),P.SubscrpEndDate__c) AS SubscriptionDueDate FROM xyz_table WHERE id='123456'

mysql - get average of the difference between two data cells

I have a table of MySQL data. Each row has its own data. In that row there is start_time and end_time. Basically, when you started doing an objective and when you finished (inserted into the database). Like a timer of sorts.
How would I get the average of of taking the unix timestamp of start_time and end_time. I know you would minus the end_time by start_time to get the difference (in milliseconds?) and from there... not sure what else.
unix_timestamp of a date column returns its representation as seconds from the epoc, so subtracting two of these will give a difference in seconds. Like any other number, you can apply the aggregate avg function to it in order to get an average:
SELECT AVG (UNIX_TIMESTAMP(end_time) - UNIX_TIMESTAMP(start_time))
FROM my_table
Once you have this result, you could manipulate it in any way you like. One useful manipulation would be to use sec_to_time to convert a number of seconds to a HH:MM:SS format (e.g., 183 seconds would be represented as 00:03:03 hours):
SELECT SEC_TO_TIME
(AVG (UNIX_TIMESTAMP(end_time) - UNIX_TIMESTAMP(start_time)))
FROM my_table

DATEDIFF() Parameter Issue

The old DATEDIFF() allowed users to use 3 parameters, and I was trying to do this so I could get hours out of my DATEDIFF rather than days, (I'm trying to show hours since a post). In my database I'm using a TIMESTAMP and this line of code to pull a value, and obviously it doesn't work because I have the extra parameter. Once I remove the 'hour' or 'hh' the query runs and returns a value in days.
SELECT DATEDIFF(hour, CURDATE(), (SELECT Post_Date FROM Post_T WHERE pk_PostID = 1) )
Is there an easy way I can return the hourly value?
Also I'm using MYSQL Version 5.5.20.
Like it says in the documentation:
DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 – expr2 expressed as a value in days from one
date to the other. expr1 and expr2 are date or date-and-time
expressions. Only the date parts of the values are used in the
calculation.
If you want the result in hours you should use Timestampdiff
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 – datetime_expr1, where datetime_expr1 and
datetime_expr2 are date or datetime expressions. One expression may be
a date and the other a datetime; a date value is treated as a datetime
having the time part '00:00:00' where necessary. The unit for the
result (an integer) is given by the unit argument.
The unit argument can be: MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.
In your case you can do:
SELECT TIMESTAMPDIFF(hour, CURDATE(), (SELECT Post_Date FROM Post_T WHERE pk_PostID = 1) )

MYSQL - datetime to seconds

I wasn't able to find out (googling, reading mysql reference manual) how to get value of DATETIME in seconds in MySQL.
I dont mean to extract seconds from datetime, but to convert it into seconds.
If by "convert to seconds", you mean "convert to an UNIX Timestamp" (i.e. number of seconds since 1970-01-01), then you can use the UNIX_TIMESTAMP function :
select UNIX_TIMESTAMP(your_datetime_field)
from your_table
where ...
And, for the sake of completness, to convert from an Unix Timestamp to a datetime, you can use the FROM_UNIXTIME function.
If you want to have the difference between two DATETIME values, use TIMESTAMPDIFF:
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument. The legal values for unit are the same as those listed in the description of the TIMESTAMPADD() function.
mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
-> 3
mysql> SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');
-> -1
mysql> SELECT TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55');
-> 128885
unit can also be HOUR which is what you asked for in one of the comments.
The unit argument can be any of the following:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
The level of usefulness of some of the other options will of course be determined by the granularity of the data. For instance, "MICROSECOND" will only have limited use if you are not storing microseconds in your DATETIME values.
Use TIME_TO_SEC in previous versions for mysql
SELECT TIME_TO_SEC(time column) FROM table
i used in mysql
TO_SECONDS(your date goes here) method to convert date to seconds from year 0
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
The function UNIX_TIMESTAMP(datetime) returns the unix time, which happens to be the number of seconds since 1-Jan-1970 0000 UTC. That may be what you need, but not if you're dealing with dates of birth, historical dates, or dates after 2037.
Starting in mysql 5.5.0 you can use to_seconds()
TO_SECONDS(FIELD_NAME)
FIELD_NAME must be DATETIME type
I have created my own query for your problem:
SELECT HOUR(`colname`) * 3600 + MINUTE(`colname`) * 60 + SECOND(`colname`)
FROM widgets
WHERE id = 1;
Use id = 1 if you have to take a specific row.
The output will be in seconds.

How do I subtract using SQL in MYSQL between two date time values and retrieve the result in minutes or second?

I want to subtract between two date time values using SQL in MySQL such that I get the interval in minutes or seconds. Any ideas? I want to run a SQL query that retrieves uses from a database who have logged in like 10 minutes from the time.
There are functions TIMEDIFF(expr1,expr2), which returns the value of expr1-expr2, and TIME_TO_SEC(expr3), which expresses expr3 in seconds.
Note that expr1 and expr2 are datetime values, and expr3 is a time value only.
Check this link for more info.
TIMESTAMPDIFF is like TIMEDIFF which Matthew states, except it returns the difference of the two datetimes in whatever units you desire (seconds, minutes, hours, etc).
For example,
SELECT TIMESTAMPDIFF(MINUTE,LogOutTime,LogInTime) AS TimeLoggedIn
FROM LogTable
Would return the number of minutes the user was logged in (assuming you stored this kind of thing in a table like that).
I would do it like this - fetch where last activity is within 10 mins of now
SELECT * FROM table WHERE last_activity >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)
SELECT TIMESTAMPDIFF(MINUTE,LogOutTime,LogInTime) AS TimeLoggedIn
FROM LogTable
This example shall ruin the time if its used by using millitary time. So for calculating millitairy time I do not recommend it Because it outputs negative values.
You can try and cast them to Unix Time stamp, and take the difference.