Calculating minutes from two different format time - sql-server-2008

My DB values save in this format
"12:07 AM"
dataType varchar in Sql Server
i want minutes b/w 2 times 2nd time is
current time
23:50 AM
23:24:43.6100000
differnce 26 minutes
but output come in negative values by executing below query
here m trying to do but output come in negative values
select datediff(minute,cast(getdate() as time),OrderDeliverTime)
from tblOrder

If the OrderDeliverTime occurs in the past, then it should be the middle parameter in DateDiff:
select datediff(minute,OrderDeliverTime,cast(getdate() as time)) from tblOrder

Related

Calculate the difference in hours between two String dates in MySQL?

I have two String columns in MySQL database. Those two columns were populated from a Java program in following way:
System.currentTimeMillis(); //first column
System.currentTimeMillis(); + someStringHours //second column; the String, someStringDays reprensents some number of days, let's say 5 hours in millis...
Which function in MySQL can be used to calculated the difference to get number of hours between these two columns?
You call them string dates but they are actually UNIX timestamps in milliseconds (also called Javascript timestamps). That's what System.currentTimeMillis() generates. It's a Java long data item, and a MySQL BIGINT data item. You can store it in a string. (You can store it that way if you must, but searching and sorting numbers stored as strings is an unreliable mess; beware!)
A typical Javascript timestamp (or UNIX timestamp in milliseconds) is a big integer like 1600858176374456. 1 600 858 176 374 456.
You can convert such a timestamp to a MySQL TIMESTAMP value with FROM_UNIXTIME() like this
FROM_UNIXTIME(column * 0.001)
Why multiply the column value by 0.001 (that is, divide it by 1000)? Because FROM_UNIXTIME() takes the timestamp in seconds, whereas System.currentTmeMillis() generates it in milliseconds.
Then you can use DATEDIFF() like this
DATEDIFF(FROM_UNIXTIME(laterTs*0.001),FROM_UNIXTIME(earlierTs*0.001))
This gives an integer number of days.
If you need the time difference in some other unit, such as hours, minutes, or calendar quarters, you can use TIMESTAMPDIFF(). This gives you your difference in hours.
TIMESTAMPDIFF(HOUR,
FROM_UNIXTIME(laterTs*0.001),
FROM_UNIXTIME(earlierTs*0.001));
You can use SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR as the time unit in this function.
Pro tip: Use your DBMS's date arithmetic functions if you possibly can. They've worked out all sorts of edge cases for you already.
And, by the way, if you declare your columns like this (Timestamp with a millisecond precision: How to save them in MySQL):
laterTs TIMESTAMP(3),
earlierTs TIMESTAMP(3),
You'll have an easier time indexing on and searching by these times.
SELECT (1600858176374-1600944576374)/(24*60*60*1000) as Days
Where (1600858176374-1600944576374) are timestamps and (246060*1000) is a mills in day

UNIX Timestamp Time Difference Average MYSQL

I am currently working on a ticket system in which I would like to work out the average amount of time it is taking staff to respond to tickets.
I have 2 columns that hold the UNIX timestamps: timestamp (when ticket was submitted) and endstamp (when ticket was closed)
SELECT AVG(TIMEDIFF(endstamp,timestamp)) AS timetaken FROM `tickets`
I'm not really sure what I am doing wrong.
Any help would be much appreciated!
A UNIX timestamp is just a representation of a point in time as a number of seconds, so basically an integer value. On the other hand, date function timestampdiff() operates on 3 parameters: a unit, and two values (or expressions) of datetime datatype (or the-like). Your query should actually raise a syntax error, since what you are giving as first argument is not a legal unit.
If you want the difference in seconds between two UNIX timestamps, just substract them, so:
SELECT AVG(endstamp - timestamp) AS timetaken FROM `tickets`

Summing timestamp returning incorrect value and format

I am looking to pull scheduled hours in a given time period. Our start and end schedule times are datetimes so I converted them to timestamps. When I dont sum them everything looks correct, but when I sum them over a time period, the output isnt in a timestamp format and the numbers are incorrect.
The query I am using:
select sal.public_name, sum(timediff(timestamp(end_time), timestamp(start_time)))
from bi.support_agents_list sal
join bi.support_sp_shifts_scheduled ss
on ss.agent_sp_id = sal.sp_id
join bi.support_sp_shifts s
on s.pk_id = ss.pk_id
where date(start_time) between '2014-01-29' and '2014-01-31'
group by sal.public_name
A few examples of results I am getting:
Agent 1: 53000 - when it should be 5.5 hours or 5:30
agent 2: 196000 - when it should be 20 hours
Any thoughts on this? I would prefer my output to be in an hour count so 5 hours and 30 min is formatted as 5.5 rather than 5:30.
try this instead of the sum
date_format(timediff(timestamp(end_time), timestamp(start_time)),
'%k hours, %i minutes, %s seconds') as thesum
like that
select sal.public_name,
date_format(timediff(timestamp(end_time), timestamp(start_time)), '%k hours, %i minutes, %s seconds') as thesum
from bi.support_agents_list sal
When doing aggregate calculations with datetime sum(datetime), the result is not what you expect (=cannot sum datetimes). You will be better off converting the datetime to seconds before the aggregate function and then convert it back to time.
Your aggregate function call would then look something like:
select sec_to_time(sum(unix_timestamp(end_time)-unix_timestamp(start_time)))
Be aware that you may reach maximum value that time datatype can contain and that unix_timestamp starts from 1970.

T-SQL Select data from multiple days between certain times

In my table I have minute data about daily temperature measurements. The table looks like:
DateTime timestamp, Float temperature
I would like to have the temperatures on different dates between a certain interval and then only show the temperature between 7am and 8pm.
I know how to get the data between dates:
SELECT [timestamp],[temperature]
FROM [meteo_data]
WHERE [timestamp] BETWEEN '2012-11-10' and '2012-11-17'
How to I implement the time restriction (7am - 8pm) as well?
Thanks a lot!!
If you are on SQL Server 2008 or above, you can use TIME datatype
SELECT [timestamp],[temperature]
FROM [meteo_data]
WHERE [timestamp] BETWEEN '2012-11-10' and '2012-11-17'
AND CONVERT(TIME,[timestamp]) BETWEEN '19:00:00' AND '20:00:00'
EDIT: Also it is recommended to use ISO (yyyymmdd) date format when using date as a string. i.e.
BETWEEN '20121110' and '20121117'
The DateTime and TimeStamp values should contain precision you need, so
SELECT [timestamp],[temperature]
FROM [meteo_data]
WHERE [timestamp] BETWEEN '2012-11-10' and '2012-11-17'
AND RIGHT([timestamp], 12) BETWEEN '19:00:00.000' AND '20:00.00.000'
You may need to adjust how many characters you are evaluating in the RIGHT predicate depending on the precision in your database. But the idea is to take all the parts that constitute the hours, minutes, seconds and miliseconds and restrict that to just those between the hours you require.

Time Over 23:59:59 in PostgreSQL?

In MySQL I can create a table with a time field, and the value can be as high as 838:59:59 (839 hours - 1 second). I just read that in PostgreSQL, the hour field cannot exceed 23:00:00 (24 hours). Is there a way around this? I'm trying to make a simple DB that keeps track of how many hours & minutes were spent doing something, so it'll need to go higher than 23 hours & some minutes. I can do this in MySQL, but I need to use PostgreSQL for this. I Googled, but didn't find what I'm looking for, so I'm hoping I just didn't use the right keywords.
Postgres has no "hour field" - it has a few date/time types which serve different needs. The type I believe best fits your needs is INTERVAL.
Although they use the same notation, there's a difference between time of day and elapsed time. Some of their values overlap, but they're different domains. 838 isn't a valid value for an hour if you're talking about a time of day. 838 is a valid value for an hour if you're talking about elapsed time.
This distinction leads to two different data types: timestamp and interval.
create table intervals (
ts timestamp primary key,
ti interval not null
);
insert into intervals values (current_timestamp, '145:23:12');
select *
from intervals;
2011-08-03 21:51:16.837 145:23:12
select extract(hour from ti)
from intervals
145
I believe you are right, but It should not be an issue to work around. Would suggest storing the UNIX time integers for when you "punch in" and out again, and then adding the delta to an int field.
This will yield the number of seconds spent, which can be translated trivially into an hours:minutes:seconds format.
The delta (difference) can be calculated by subtracting the start timestamp from the end timestamp.
you could use a datetime field... 839 hours being something on the order 34.9 days...