date_trunc('minute', timestamp) equivalent in MYSQL - mysql

What is the date_trunc('minute', timestamp) equivalent in MYSQL? Thanks in advance

I like to use date_format() for this:
date_format(timestamp, '%Y-%m-%d %H:%i:00')
Or you can use date arithmetics (this works only if our initial value has no fractional seconds):
timestamp - interval extract(second from timestamp) second

One method is to convert to seconds, divide by sixty, truncate, and convert back:
select from_unixtime(floor(unix_timestamp(timestamp) / 60)*60)
What is handy about this is that it can be used for other intervals, such as every 15 minutes (or whatever) by tweaking the logic.

This is the simplest solution I've found.
MySQL MINUTE() returns a MINUTE from a time or datetime value.
MINUTE(time1)

Related

MySQL TIME_TO_SEC with fractional seconds

I currently have fields that use a time(6) type. Values would be something like 00:01:03.125000. When I use
SELECT TIME_TO_SEC("00:01:03.125000")
I want it to give me 63.125 or 63.125000, but instead it rounds it to 63.
Is there a MySQL function that will provide me with the time value in fractional seconds? If not, what workaround should I use?
You can add MICROSECOND to the seconds
TIME_TO_SEC("00:01:03.125000") + MICROSECOND("00:01:03.125") / 1000000
Result: 63.125
or
use TIMESTAMPDIFF function with MICROSECOND
TIMESTAMPDIFF( MICROSECOND, CURDATE(), ADDTIME(CURDATE(), "00:01:03.125000") ) / 1000000
Result: 63.125

How to get the start Unix timestamp of current hour in MySQL?

UNIX_TIMESTAMP() function in MySQL gives the unix timestamp of NOW.
But I want to get the start unix timestamp of current hour.
is there any way to get it?
Suppose, the current time is = 2016-03-07 13:05:23
UNIX_TIMESTAMP() -> 1457334323
I want to get the unix timestamp of 2016-03-07 13:00:00
Expected Result:1457334000
Try this:
select UNIX_TIMESTAMP(DATE_FORMAT(NOW(), '%Y-%m-%d %H-00-00'));
You can use UNIX_TIMESTAMP() function to do the job done.
SELECT (
UNIX_TIMESTAMP(NOW()) - (MINUTE(NOW()) * 60 + SECOND(NOW()))
) AS startUnixTimestampOfCurrentHour;
Explanation:
Suppose, Now() returns 2016-03-07 13:05:23.
Now if you look closely then you just need to avoid the minute and second part. Minute and Second are expected to have zero value.
So if you subtract the minuteand second from now then you will reach to the start of the current hour. And then take the UNIX_TIMESTAMP of this particular time.
OR
SELECT (UNIX_TIMESTAMP() DIV 3600)*3600 AS startUnixTimestampOfCurrentHour;
select unix_timestamp(date_format(now(), "%Y-%m-%d %H:00:00"));
You could use DATE_FORMAT to remove minutes/second part:
SELECT UNIX_TIMESTAMP(DATE_FORMAT(NOW(), '%Y-%m-%d %H:00:00')) AS result
SqlFiddleDemo

Mysql Function to find total no of seconds between two dates

Say i've a from date as 17/10/2012 and to date as 18/10/2012.How will i find total no of seconds that is available ?
Update I do not want to select a row which has exceed to date ?
Thanks in advance!
Here is the working demo.
http://sqlfiddle.com/#!2/d41d8/2869
SELECT UNIX_TIMESTAMP('2012-10-19') - UNIX_TIMESTAMP('2012-10-18') as differece_seconds;
"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."
You can simply use it with date coulmn.
Please check : http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp
Assuming your columns are proper DATE/DATETIME columns and not the date strings in your question, subtract the values of UNIX_TIMESTAMP()
SELECT UNIX_TIMESTAMP(date1_column) - UNIX_TIMESTAMP(date2_column) AS difference_seconds
If you have stored dates in the string format you posted above (which is a bad idea), you will need STR_TO_DATE() to first parse them into proper MySQL dates.
SELECT UNIX_TIMSTAMP(STR_TO_DATE('17/10/2012','%d/%m/%%Y')) - UNIX_TIMSTAMP(STR_TO_DATE('18/10/2012','%d/%m/%%Y')) AS difference_seconds
Use UNIX_TIMESTAMP() to get the seconds since epoch for a specific date. Then just subtract both values.
So assuming the values (in some DATE or DATETIME) are stored in col1 and col2 respectively, use can use something like this:
SELECT UNIX_TIMESTAMP( col1 ) - UNIX_TIMESTAMP( col2 ) AS diff FROM yourTable;
select timestampdiff(second,'2012-10-16','2012-10-18');
output will be
172800

MySQL Select rows <= now(), using separated time fields

I have a table 't' with date(yyyy-mm-dd), hour(1-12), minute(00-59), ampm(a/p), and timezone(pst/est) fields.
How can I select the rows that are <= now()? (ie. already happened)
Thank you for your suggestions!
edit: this does it without attention to the hour/minute/ap/tz fields:
SELECT * FROM t.date WHERE date <= now()
Here's one way to do it - combine all your seconds, minutes, etc into a date and compare to NOW(), making sure you do the comparison in the same time-zone. (Untested):
SELECT *
FROM t
LEFT JOIN y ON t.constant=y.constant
WHERE CONVERT_TZ(STR_TO_DATE(CONCAT(date,' ',hour,':',minute,' 'ampm),
'%Y-%m-%d %l:%i %p' ),
timezone,"SYSTEM") < NOW();
If your hour is 01 - 12 not 1-12 then use %h instead of %l in the STR_TO_DATE.
The STR_TO_DATE tries to stick your date and time columns together and convert them into a date.
The CONVERT_TZ(...,timezone,"SYSTEM") converts this date from whatever timezone is specified in the timezone column to system time.
This is then compared to NOW(), which is always in system time.
As an aside, perhaps you should make a single column date using MySQL's date datatype, as it's a lot easier to do arithmetic on that!
For reference, here is a summary of very useful mysql date functions where you can read up on those featuring in this answer.
Good luck!
SELECT * FROM t
WHERE `date`<=DATE_SUB(curdate(), INTERVAL 1 DAY)
OR (
`date`<=DATE_ADD(curdate(), INTERVAL 1 DAY)
AND
CONVERT_TZ(CAST(CONCAT(`date`,' ',IF(`hour`=12 AND ampm='a',0,if(ampm='a',`hour`,`hour`+12)),':',`minute`,':00') AS DATETIME),'GMT',`timezone`)<=NOW()
)
Rationale for date<=DATE_[ADD|SUB](curdate(), INTERVAL 1 DAY):
The fancy conversion is quite an expensive operation, so we don't want it to run on the complete table. This is why we pre-select against an UNCHANGED date field (possibly using an index). In no timezone can an event being more than a day in current timezone's past be in the future, and in no timezone can an event more than a day in the curent timezone's future be in the past.

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.