Convert timestamp to X days X hours X minutes ago - mysql

I've created a stored procedure in MySQL Server 5.1.
How can I convert a timestamp to a string that represents the days, hours, and minutes difference between that timestamp and now?
For example, if the timestamp is 5 hours and 3 minutes ago I'll get '5 hours 3 minutes ago'.

select date_format(timediff(current_timestamp,last_timestamp),
'%k hours, %i minutes, %s seconds ago');
If you want more luxury you can do something like:
select concat
(
if(date_format(timediff(ts1,ts2)'%k')='0'
,'',date_format(timediff(ts1,ts2)'%k hours'),
if(date_format(timediff(ts1,ts2)'%i')='0'
,'',date_format(timediff(ts1,ts2)'%k minutes'),
if(date_format(timediff(ts1,ts2)'%s')='0'
,'',date_format(timediff(ts1,ts2)'%k seconds')
)
Plus a few extra spaces here and there.
If one of the timestamps is null naturally the result will also be null, you'll have to make sure it is not, or use ifnull(`timestamp`,now()) to fix that.
See: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff

Have a look at the MySQL reference page for date and time functions at
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime
Edit: Since I assume you are using Unix timestamps, the way to go is
FROM_UNIXTIME(timestamp, format)

Related

Subtract 5 hours from a datetime value that is type timestamp with timezone

I am querying a table that has a datetime column and the value is in the format time stamp with time zone. I've tried doing a select hour(timestamp,-5) as NTime and different variants of that, but the furthest I get is an error stating the timestamp is not a valid name/type. I'm officially going off the deep end on this....
Basically, I just need the new alias column values to be a time stamp that is 5 hours behind the timestamp that is in the original table. Thank you all in advance!!
MariaDB / MySQL doesn't have a "timestamp with timezone" data type.
DATETIMEs are simple wall time, and TIMESTAMPs are UNIX time_t timestamps (the number of seconds since 1970-01-01T00:00:00UTC).
You can convert DATETIME values from one time zone to another by with tz_convert().
SELECT tz_convert('2022-04-08 21:53', 'America/Chicago', 'UTC')
for example.
Or, just to do date arithmetic you can do stuff like this.
SELECT '2022-04-08 21:53' - INTERVAL 5 HOUR

How to sum time interval stored as string in MySQL like 5 days 10:20:00

I need to write a select query to sum the time interval from MySQL table where the time interval is stored as text and in the format similar to following
10 days 3:28:31
In the PostgreSQL query we can simply use ::interval and it converts above to interval and we can use Sum method over it in PostgreSQL query but I am unable to do the same in MySQL. Any help would be appreciated.
MySQL does not have an interval data type. It does use the interval keyword -- which is a bit confusing. But that is a syntactic element, rather than a data type.
One thing you can do is use the time data type. This supports times up to 838 hours -- or about 35 days. That is enough for many purposes.
Otherwise, the recommendation is to use a single time unit and to store the value as a numeric quantity. For instance, "5 days 10:20:00" would be:
5.43055555556 days (5 + 10 / 24 + 20 / (24*60))
130.333333333 hours
7820 minutes

MySQL select rows that are exactly 7 days old FROM TIMESTAMP

first of all, I know that my question is very similar to that one:
MySQL select rows from exactly 7 days ago
the difference is that my dates are stored in the database as a timestamp.
I know that I can use FROM_UNIXTIME to get the date from the timestamp, the thing is, in another answer I read that was very resource consuming (because the timestamp field has to be converted to date in all the records before comparing).
DATE(from_unixtime(timestamp)) = CURRENT_DATE()
Is there any optimized way to do this?
Turn it around: calculate the unix timestamp of the target date first and use that.
WHERE timestamp = UNIX_TIMESTAMP(NOW() - INTERVAL 7 DAY)
MySQL should calculate that value once and use it all the time (needs testing though). If it doesn't, use a variable or code.

How to compare variable amount of days using UNIX timestamp (stored as int)

I need to pull a variable amount of days of data from a MySQL database that stores the date as a UNIX timestamp in an int column.
For example, if I need the last 5 days of data, what would my query be?
(All queries would start from current date and would go back x amount of days).
Timestamp is considered one of the Date and Time types and therefore any of the Date Time Functions can be used on it.
SELECT * FROM your_table
WHERE Ftimestamp_column > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 5 DAY));
I've never tried it but there's a MySQL function to convert unix timestamps into MySQL dates and then you can use DATE_SUB() or whatever. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime

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.