MySQL TIME_TO_SEC with fractional seconds - mysql

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

Related

date_trunc('minute', timestamp) equivalent in 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)

MySQL UNIX_TIMESTAMP(now()) - current time in milliseconds

Is there a MySQL way to query based on current MySQL time in milliseconds?
I'm trying:
SELECT UNIX_TIMESTAMP(), UNIX_TIMESTAMP(NOW()) as now_in_mili
but both columns return the same (the 1970 epoch time).
I'm expecting 'now_in_mili' to print current date in milliseconds such as
it is possible in JavaScript:
Date.parse(new Date())
You need to pass an argument to the NOW() function to specify how many digits of fractional seconds you want it to include. It supports microseconds, but if you want milliseconds you can just use NOW(3) and then multiply the result by 1000, like this:
SELECT UNIX_TIMESTAMP(NOW(3))*1000 as now_in_mili

mysql timestampdiff always returning null?

I am using version 14.4 of mysql and I am trying to execute the following query:
SELECT TIMESTAMPDIFF(MINUTE, MINUTE(NOW()), NOW())
This should return a timestamp that is on the current hour, but it's always returning null. TIMESTAMPADD works just fine, I am only having trouble with this function. I have looked for answers to this problem through google and mysql documentation but I couldn't find anything.
Does anyone have any an idea on what's going wrong?
My full goal is a query that returns how many minutes are left from now until 5 of the next hour. For example. If its 1:30, our target time is 1:55, so the query would return 25
If you want the hour
SELECT CURTIME()
That query you posted is absurd,or be more clear about what you want.
I believe you're trying to floor the current UNIX timestamp to the current hour? If so, why not be explicit about it?
SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP() % 3600;
Based on your edits, you can also calculate the difference to the 5 minute mark preceding the next hour as follows:
SELECT MINUTE( TIMEDIFF(
NOW(),
FROM_UNIXTIME( UNIX_TIMESTAMP() - UNIX_TIMESTAMP() % 3600 + 3600 - 5*60 )
) );
This is just a proof-of-concept query; I haven't yet accounted for rounding the current time to the minute (because I don't know if you want to go up or down), nor handled the edge case where the current time is within 5 minutes of the next hour already (e.g. 1:59).

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 - 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.