Time stamp calculation on SQL queries - mysql

I'm trying to display the total travel time that each customer in data time format (00:00:00)
But I'm confused to whether I should just do
SEC_TO_TIME(SUM(endtime - starttime))
or
SEC_TO_TIME(SUM(TIME_TO_SEC(endtime - starttime)))
or
SEC_TO_TIME(SUM(TIME_TO_SEC(endtime) - TIME_TO_SEC(starttime))
if endtime and startime is in datetime format
which one should be the right way to do it. I'm getting a different result for first and the second one

1st:
convert endtime and starttime into timestamp using UNIX_TIMESTAMP
2nd:
subtract them
note: the result will be in seconds
(UNIX_TIMESTAMP(endtime) - UNIX_TIMESTAMP(starttime))
to determine how much time did the costumer consume
3rd:
convert the result into time
SEC_TO_TIME( (UNIX_TIMESTAMP(endtime) - UNIX_TIMESTAMP(starttime)) )
so your final query should be like this
SELECT SEC_TO_TIME( (UNIX_TIMESTAMP(endtime) - UNIX_TIMESTAMP(starttime)) ) FROM travel

Of your three options, I would recommend:
SEC_TO_TIME(SUM(TIME_TO_SEC(endtime)
- TIME_TO_SEC(starttime))
First, I think this is clearest on what you want to do:
Convert the date/times to seconds
Add up the seconds
Convert back to a time
Second, MySQL treats date/time values as numbers in a numeric context. This can produce strange results because 2018-09-13 is turned into 20,180,913, and that is not usually what you want.

Related

SQL showing current timestamp in different formats Mysql

I need to show current UTC timestamp in a format '2021/05/10T18:30:36Z'
SELECT UTC_TIMESTAMP() FROM XYZ
gives me 2021-05-10 18:30:36
how do i add the / instead of - and use T and Z
select DATE_FORMAT(UTC_TIMESTAMP(),'%Y/%m/%dT%TZ')
2021/05/10T18:51:07Z
Note that T doesn't really mean anything. And Z means UTC ZERO timezone, which is always the case with the UTC_TIMESTAMP function. Thus I have somewhat "hardcoded" those letters at the right place , and they are not real variables accepted by DATE_FORMAT()

MySQL SEC_TO_TIME gives hh:mm:ss.000000

As said in the caption I am wondering why the SEC_TO_TIME-Function of MySQL gives me that Zeros at the end.
Refering to the docu (http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_sec-to-time) that shouldn't happen (I am using MySQL 5.0.11).
Any Idea why this Zeros appears and how to get rid of them? To much zeros for displaying miliseconds.
Sine the zeros doens't break MySQLs Date-funcions, it's more a "I don't like that"-Question rather than a real Problem (at least till now^^)
// EDIT: I just figured out that the zeros aren't coming from the SEC_TO_TIME but from the FROM_UNIXTIME()-Function. Thx to #Abhik Chakraborty to ask for the input!
// EDIT2: I used FROM_UNIXTIME(last_try, '%Y-%m-%d %H:%i:%s') to get rid of the zeros. But When I do TIME(FROM_UNIXTIME(last_try, '%Y-%m-%d %H:%i:%s')) the zeros are back. Why??
Seems like every function adds the zeros back. Using SEC_TO_TIME on a simple integer-value also gives zeros...
Here is the whole query iam using:
SELECT
SEC_TO_TIME(FLOOR(TIME_TO_SEC((TIME(FROM_UNIXTIME(`last_try`))))/1800)*1800)
FROM `last48h`
The query reads the timestamp, gets only the time, converts it to seconds, breaks the seconds into half-hours (/1800 gives 0 < x < 48) rounds down and converts back to time
SEC_TO_TIME produces a TIME data type for its result. You can format that as you wish with DATE_FORMAT.
If you actually need subsecond time resolution you'll need to move to version 5.6.4 or beyond.
When you directly SELECT any sort of TIME data type to display, you get a default TIME-to-string conversion operation. The default TIME-to-string conversion in some generations of MySQL yields a string ending in hh:mm:ss+zz00. +zz00 is a timezone indicator, and often displays as +0000. Any chance that's what you're seeing?
It doesn't make sense to try to handle a UNIX_TIMESTAMP() style number of seconds using SEC_TO_TIME(). As of mid-2014 the current unix timestamp value is above 1.39 gigaseconds. TIME data types are used for stuff like elapsed times, and have a limit of just under 839 hours (3 megaseconds, precisely 3020399 seconds), and silently truncate their values.
For example, this is a good use of SEC_TO_TIME:
SELECT SEC_TO_TIME(end_timestamp - start_timestamp) AS duration
edit
Strangely enough, this query
SELECT
SEC_TO_TIME(FLOOR(TIME_TO_SEC((TIME(FROM_UNIXTIME(UNIX_TIMESTAMP()))))/1800)*1800) AS a,
FLOOR(TIME_TO_SEC((TIME(FROM_UNIXTIME(UNIX_TIMESTAMP()))))/1800)*1800 AS b,
TIME_TO_SEC((TIME(FROM_UNIXTIME(UNIX_TIMESTAMP()))))/1800 AS c,
FROM_UNIXTIME(UNIX_TIMESTAMP()) AS d,
FROM_UNIXTIME(UNIX_TIMESTAMP() - UNIX_TIMESTAMP() % 1800) as e
doesn't show any of the 0000 stuff through the phpmyadmin instance I use.
By the way, most people who round time to the nearest interval (a half-hour in your case) prefer to use a modulo and a subtraction; it's less dependent on implicit numerical type conversion than your method.
SELECT TIME(FROM_UNIXTIME(last_try - last_try%1800))
does what the query in your question does.
I had the same problem with the 'SEC_TO_TIME' function.
I had overlooked the fact that I was storing timestamps as a VARCHAR.
I changed my datatypes from VARCHAR to BIGINT and it is formatting the output values as expected (hh:mm:ss).
Try to use TIME_FORMAT with %k specifier it should help.

MySql - Bad format for Time 'hhh:mm:ss' in column x

In MySQL, I am trying to get difference between two timestamp value and storing the result in time column. But sometimes the result comes in 'hhh:mm:ss' format. While trying to access that column in Java using Result.getTime(), it is throwing error saying 'Bad format for time in column x'.
To get better idea, store the result of following query in time column and try to access this value in Java.
SELECT SEC_TO_TIME(ABS(TIMESTAMPDIFF(SECOND,'2013-01-26 19:03:48','2013-02-15 06:59:36'))) as 'RESULT';
What should I do to get result even if it has 'hhh:mm:ss' format (without any error)?
Thanks in advance.
I assume you run query and result set contain the result
String hourMinSec=resultset.getString("RESULT");
String[]result=hourMinSec.split(":");
int hour=Integer.parseInt(result[0]);
int min=Integer.parseInt(result[1]);
int second=Integer.parseInt(result[2]);
Expressing difference between two dates as date is meaningless i think. Just to answer your question if you want to create time you can use following
Time time =new Time(hour, min, second);
But i feel its meaningless.
You can't express the difference between two dates as another date. For example if you will got 31 days difference you can't say if it is 1 month or 1 month and 1 day.
You should create your own object to storage this data.

why this MySQL SELECT doesn't include the right dates?

The main problem is, that I have stored in database datetime , not the date (what I need). Ok never mind.
I have thousands of reports stored each day.
I need to LEFT by 10 my datetime_view (to cut the time) and everything's fine. Except this. I'm trying to figure out why do I have to put in the condition + one day from the future? Otherwise it won't search what I want.
SELECT
LEFT(datetime_view,10),
count(type)
FROM reports
WHERE
type IN (1,2,5)
AND
datetime_view>='2012-10-28'
AND
datetime_view<='2012-11-04'
group by LEFT(datetime_view,10);
You can see I must search from the future. Why??
It gives me an output from 28.10 to 3.11 ....
don't use string operations on date/time values. MySQL has a huge set of functions for date/time manipulation. Try
GROUP BY DATE(datetime_view)
instead, which will extract only the date portion of the datetime field. Your string operation is not y10k compliant. Using the date() function is.
As for your plus one day, consider how the comparisons are done: A plain date value, when used in date/time comparisons, has an implicit 00:00:00 time value attached to it, e.g. all dates have a time of "midnight".
i think it's better to use DATE(datetime_view) to cut the time instead of LEFT(datetime_view,10), also on the where condition:
DATE(datetime_view) <= '2012-11-03'

Mysql time stamp queries

I have a column that uses time stamp. My question is I am a bit confused about how to make queries against it,how would I say
Where $time is after X date
Are queries made in local time or CUT?
When I just try to do where andthe post date /time I get an error because of the space and if I quote it I think it takes it as a string : /
What format do I use for the date in the WHERE clauss !?!?
You can use the normal logical comparisons, for example:
SELECT * FROM table WHERE date >= '2010-01-31'
SELECT * FROM table WHERE date >= '2010-01-31 12:01:01'
Time is generally in your current local time, but you can run the query "SELECT CURTIME()" to check. Also, make sure you have the year-month-date in the right order... that can cause issues.
The manual has more details:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
Assuming you talk about TIMESTAMP column type (not Unix timestamp) the format is either 'YYYY-MM-DD HH:MM:SS' (quoted) or YYYYMMDDHHMMSS
Atually, in the first case you can use any spearators you wish (or none), only numbers are taken into ccount