Get the time difference in minutes between two timestamps (Mysql) - mysql

Hi I tried the following:
timediff(`date2`, `date1`) which gives me the time difference but if the days are different it does not account for the day difference. so if date2 is yesterday and date1 is today it will provide something like this: 00:00:07
I saw the timestampdiff function a couple of times, but I am using MySQL in Domo, and this function is not offered there. Any other suggestion how to get the time difference between two timestamps (where days are different) in minutes?

SELECT TIMESTAMPDIFF(MINUTE, '2020-01-07T12:17:03', '2020-01-06T13:14:02')
returns -1383
you can change MINUTE to SECOND or other formats as well.
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_timestampdiff
edit: sorry, just read that the function is not available in your environment...
therefore I suggets to convert the datetimes to seconds and work your way up from there, e.g.
SELECT (UNIX_TIMESTAMP('2020-01-07T12:17:03') - UNIX_TIMESTAMP('2020-01-06T13:14:02')) / 60

Related

Compare creation dates of things that may have been made before christ

I'm thinking about making a project in a database with a large amount of objects / people / animals / buildings, etc.
The application would let the user select two candidates and see which came first. The comparison would be made by date, or course.
MySQL only allow dates after 01/01/1000.
If one user were to compare which came first: Michael Jackson or Fred Mercury, the answer would be easy since they came after this year.
But if they were to compare which came first: Tyranosaurus Rex or Dog, they both came before the accepted date.
How could I make those comparisons considering the SQL limit?
I didn't do anything yet, but this is something I'd like to know before I start doing something that will never work.
THIS IS NOT A DUPLICATE OF OTHER QUESTIONS ABOUT OLD DATES.
In other questions, people are asking about how to store. It would be extremely easy, just make a string out of it. But in my case, I'd need to compare such dates, which they didn't ask for, yet.
I could store the dates as a string, using A for after and B for before, as people answered in other questions. There would be no problem. But how could I compare those dates? What part of the string I'd need to break?
You could take a signed BIGINT field and use it as a UNIX timestamp.
A UNIX timestamp is the number of seconds that passed since January 1, 1970, at 0:00 UTC.
Any point in time would simply be a negative timestamp.
If my amateurish calculation is correct, a BIGINT would be enough to take you 292471208678 years into the past (from 1970) and the same number of years into the future. That ought to be enough for pretty much anything.
That would make dates very easy to compare - you'd simply have to see whether one date is bigger than the other.
The conversion from calendar date to timestamp you'd have to do outside mySQL, though.
Depending on what platform you are using there may be a date library to help you with the task.
Why deal with static age at time of entry and offset?
User is going to want to see a date as a date anyway
Complex data entry
Three fields
year smallint (good for up to -32,768 BC)
month tinyint
day tinyint
if ( (y1*10000 + m1*100 + d1) > (y2*10000 + m2*100 + d2) )
OK I had an idea.
Store the age in days, since the hours/seconds are irrelevant for this case.
Christ's age in days: -2015 * 365.
Dog's age in days: -40000 * 365.
In order to make precise calculations, I'd only need an extra field with the date I have added the values. Then add to the "age in days" the difference in days from the day I have added the register, from the day the user is making the comparison.
For example:
Dog's age has been added in 29/12/2015 and the age in days is -40000 * 365.
User is making a comparison on day 29/01/2016.
The difference in days between the two dates is 31 days.
So dog's age in days should be -40000 * 365 - 31.
Using an unsigned big int can do the trick.
Thanks to Pekka for suggesting using negative numbers for any date before the current date.

Converting Integer to Time

We have an database that has a table which stores schedule information, including a clock in and clock out column. The problem is that whomever created this table made these to attributes as integers instead of time or datetime (This could also have been forced by the software that creates the schedule). So, for instance, instead of saying 8:00:00, it says 480 (the number of minutes that have passed that day). 18:00 (6 PM) shows 1080, Midnight is 1440, etc.
I have to query this for a report and do a calculation based off of the scheduled punches vs the actual hours worked which is stored as a time datatype. I am trying to convert the integer minutes into time of day in the select statement in order to have a CTE I can work with for multiple comparisons. So far this is what I've come up with (keep in mind the schedule is done by quarter hour increments, hence the .25, .5, .75, etc.)
SELECT CASE CAST(ClockIN AS decimal) / 60
WHEN .25 THEN CAST('00:15:00.0000000' AS time)
WHEN .5 THEN CAST('00:30:00.0000000' AS time)
WHEN .75 THEN CAST('00:75:00.0000000' AS time)
WHEN 1 THEN CAST('01:00:00.0000000' AS time)
.....
WHEN 24 THEN CAST('00:00:00.0000000' AS time)
END AS ClockIn
I am trying to have clean code and not do too many calculations that take up resources every time the report is ran. Is there an easier way to do all of this, am I not thinking out of the box enough? So far this is the only way I can think of to accomplish what I need, which is an integer representing passed time converted to a timestamp Any advice would be appreciated!
You can create a time and then use DATEADD to just add minutes to the time. So at 480 minutes, you'd add it to the new time created "00:00" and it should leave you at 8:00 AM.
DATEADD(minute, ClockIN, '00:00')

SQL, querying by date intervals

I've got a dataset that I want to be able to slice up by date interval. It's a bunch of scraped web data and each item has a unix-style milisecond timestamp as well as a standard UTC datetime.
I'd like to be able to query the dataset, picking out the rows that are closest to various time intervals:
e.g.: Every hour, once a day, once a week, etc.
There is no guarantee that the timestamps are going to fall evenly on the interval times, otherwise I'd just do a mod query on the timestamp.
Is there a way to do this with SQL commands that doesn't involve stored procs or some sort of pre-computed support tables?
I use the latest MariaDB.
EDIT:
The marked answer doesn't quite answer my specific question but it is a decent answer to the more generalized problem so I went ahead and marked it.
I was specifically looking for a way to query a set of data where the timestamp is highly variable and to grab out rows that are reasonably close to periodic time intervals. E.g.: get all the rows that are the closest to being on 24 hour intervals from right now.
I ended up using a modulus query to solve the problem: timestamp % interval < average spacing between data points. This occasionally grabs extra points and misses a few but was good enough for my graphing application.
And them I got sick of the node-mysql library crashing all the time so I moved to MongoDB.
You say you want 'closest to various time intervals' but then say 'every hour/day/week', so the actual implementation will depend on what you really want, but you can use a host of standard date/time functions to group records, for example count by day:
SELECT DATE(your_DateTime) AS Dt, COUNT(something) AS CT
FROM yourTable
GROUP BY DATE(your_DateTime)
Count by Hour:
SELECT DATE(your_DateTime) AS Dt,HOUR(your_DateTime) AS Hr, COUNT(something) AS CT
FROM yourTable
GROUP BY DATE(your_DateTime), HOUR(your_DateTime)
See the full list of supported date and time functions here:
https://mariadb.com/kb/en/date-and-time-functions/

Timzone conversions on date only and time only - is it necessary?

We've been working on implementing timezone support for our Web app.
This great SO post has helped us a bunch: Daylight saving time and time zone best practices
We've implelmented the OLSON TZ database in MYSQL and are using that for TZ conversions.
We're building a scheduling app so:
We are storing all our bookings which occur on a specific date at a specific time in UTC time in DateTime fields and converting them using CONVERT_TZ(). This is working great.
What we aren't so sure about is stuff like vacations and breaks:
Vacations are just Date references and don't include a time portion. Because CONVERT_TZ() doesn't work on date objects we are guessing that we are best to just store the date value as per the user's timezone?
id1 id3 startDate endDate
-----------------------------
3 6 2010-12-25 2011-01-03
4 3 2010-09-22 2010-09-26
Same thing with recurring breaks during stored for each day of the week. We currently store their breaks indexed 0-6 for each day of the week. Because these are just time objects we can't use CONVERT_TZ() and assume we should just store them as time values in the user's time zone?
bID sID dayID startTime endTime
--------------------------------
1 4 1 12:00:00 14:00:00
2 4 4 13:30:00 13:30:00
In this case with vacations and breaks we would only compare them to booking times AFTER the booking times have been converted to the user's local time.
Is this the correct way to handle things, or should we be storing both vacations and breaks in some other way so that we can convert them to UTC (not sure how this would work for breaks).
Thanks for your assistance!
The two storage formats look fine. You just need to convert them to the user's local time when you pull them out of the table.
Actually, for the breaks table I presume they're already nominally in local time, so you just compare directly against the local time of the appointment.
I don't understand your question well enough to say my answer is 100% correct for you. But I think what you need to do is store the DateTime in "local" time and also store the timezone. This way you have it correct even if daylight savings time shifts (which happens).
Good article at http://blogs.windwardreports.com/davidt/2009/11/what-every-developer-should-know-about-time.html (yes by me).

Best way to store time interval values in MySQL?

Stupid easy problem, but I haven't been able to find an elegant solution. I want to store time intervals in a MySQL columns, for instance:
1:40 (for one hour, 40 minutes)
0:30 (30 minutes).
Then be able to run queries, summing them. Right now I store them as INT values (1.40), but I have to manually do the addition (unless I'm missing an easier way).
The TIME column type only stores upto 900 hours (about, I think), so that's (almost) useless for me since I am tracking upwards of hundreds of thousands of hours (I store one field with a summation of many different entries).
Thanks!
store just the minutes, so 1:40 gets stored as 100. this makes for easy addition: 100 + 30 = 130. when you display, do the math to convert back to hours:minutes. 130 minutes -> 2:10.
I would simply store them in an INT field as seconds or minutes (or whatever the lowest time value you are working with).
As an example, you want to store the following time value 1 hr 34 min 25 seconds:
That is 5665 seconds. So just store the value as 5665 in an INT field
Later, lets say you want to store the time value 56 min 7 seconds:
That's 3367 seconds.
Sum up everything later: 5665 + 3367 = 9032 seconds
Convert that back to hours, minutes, seconds, you get 2 hrs 30 min 32 seconds. Yes, you have to do the math to make the conversion, but it's a very simple calculation and it's not at all machine intensive since you are only doing it once, either before you store the INT or once, after you retrieve the INT.
You can definitely use an int field for this, especially since MySQL provides the DATE_ADD and DATE_SUB functions for using integer units of time alongside date and datetime types in date artihmetic.
For example, if you have a datetime column eventDateTime and you have a duration column durationMinutes you can calculate the ending datetime using:
DATE_ADD(eventDateTime,INTERVAL durationMinutes MINUTE)
I know this is not the kind of time interval you are talking about, when I when I searched around this is about the only relevant SO question I found, so to help out other lost souls like myself I thought I would post what I am doing now.
I am storing a Subscription length, which rather than precise values like "number of seconds" or even minutes is either Days or Months. So in my case I have a "duration" INT and a "duration_unit" ENUM of ('days','months').
So for a "6 month" subscription rather than trying to calculate how many minutes are in a 6 months (which varies depending on which 6 months you are talking about) I just store "6" and "months".
With PHP's mktime() method it is easy and more accurate to calculate time intervals of +6 months.
If you want to store them as hours, and thus keep the integer small, you can take the number of minutes and divide by 60.
So 1:40 becomes 100/60 = 1.66 , :30 becomes 30/60 = .5. Now you can just add them up normally:
1.66 + .5 = 2.16
and then you have the number of hours as the whole, and the decimal part is the number of minutes over 60, so that would be
.16 * 60 = 10
so it's 2:10
Your next best option is to see if MySQL can do base60.