How to compare UNIX DATA and TIME - mysql

I have: (this example works)
SELECT *
FROM messages m
WHERE
m.create_timestamp > STR_TO_DATE('2016-01-28 05:06:38', '%Y-%m-%d %H:%i:%s')
ORDER BY m.create_timestamp
LIMIT 100;
but I have this '2016-01-28 05:06:38' datetime in UNIX FORMAT.
I tried:
m.create_timestamp > FROM_UNIXTIME(1453946798, '%Y-%m-%d %H:%i:%s')
But this doesn't work.
I want to compare date in UNIX FORMAT: m.create_timestamp > 1453946798.
Help please!

UNIX format is just the number of milliseconds since 1970-01-01 00:00:00 UTC. So you can just compare the values between them. The highest value will be the point that is later in time.
A simple:
m.create_timestamp > 1453946798
> 1453946798 means it's after 2016-01-28 05:06:38
< 1453946798 means it's before 2016-01-28 05:06:38
Make sure the unix timestamps have the same precision though. Sometimes it's the number of seconds since epoch instead of milliseconds for precision and storage size reasons.
If you have a timestamp in milliseconds to compare with your 1453946798, divide it by 1000 and floor it before comparing the timestamps.
To convert a DATETIME to a TIMESTAMP, you can use the following:
UNIX_TIMESTAMP('2015-01-15 12:00:00');
Of course, replace '2015-01-15 12:00:00' with the date to convert.

Try this
SELECT * FROM messages m
WHERE
m.create_timestamp > FROM_UNIXTIME(create_timestamp)
ORDER BY m.create_timestamp
LIMIT 100

I think you want unix_timestamp(); this command will convert a datetime to a unix timestamp: unix_timestamp('YYYY-MM-DD HH:MM:SS').

Related

How to get the start Unix timestamp of current hour in MySQL?

UNIX_TIMESTAMP() function in MySQL gives the unix timestamp of NOW.
But I want to get the start unix timestamp of current hour.
is there any way to get it?
Suppose, the current time is = 2016-03-07 13:05:23
UNIX_TIMESTAMP() -> 1457334323
I want to get the unix timestamp of 2016-03-07 13:00:00
Expected Result:1457334000
Try this:
select UNIX_TIMESTAMP(DATE_FORMAT(NOW(), '%Y-%m-%d %H-00-00'));
You can use UNIX_TIMESTAMP() function to do the job done.
SELECT (
UNIX_TIMESTAMP(NOW()) - (MINUTE(NOW()) * 60 + SECOND(NOW()))
) AS startUnixTimestampOfCurrentHour;
Explanation:
Suppose, Now() returns 2016-03-07 13:05:23.
Now if you look closely then you just need to avoid the minute and second part. Minute and Second are expected to have zero value.
So if you subtract the minuteand second from now then you will reach to the start of the current hour. And then take the UNIX_TIMESTAMP of this particular time.
OR
SELECT (UNIX_TIMESTAMP() DIV 3600)*3600 AS startUnixTimestampOfCurrentHour;
select unix_timestamp(date_format(now(), "%Y-%m-%d %H:00:00"));
You could use DATE_FORMAT to remove minutes/second part:
SELECT UNIX_TIMESTAMP(DATE_FORMAT(NOW(), '%Y-%m-%d %H:00:00')) AS result
SqlFiddleDemo

MySql timestamp rounding then reformatting in human readable format

I have the following query from Group OHLC-Stockmarket Data into multiple timeframes - Mysql.
SELECT
FLOOR(MIN(`timestamp`)/"+period+")*"+period+" AS timestamp,
SUM(amount) AS volume,
SUM(price*amount)/sum(amount) AS wavg_price,
SUBSTRING_INDEX(MIN(CONCAT(`timestamp`, '_', price)), '_', -1) AS `open`,
MAX(price) AS high,
MIN(price) AS low,
SUBSTRING_INDEX(MAX(CONCAT(`timestamp`, '_', price)), '_', -1) AS `close`
FROM transactions_history -- this table has 3 columns (timestamp, amount, price)
GROUP BY FLOOR(`timestamp`/"+period+")
ORDER BY timestamp
In my select statement, FLOOR(MIN(timestamp)/"+period+")*"+period+" AS timestamp,
I am trying to understand what it is doing. and
I need to convert this back to a mysql date/time Y-M-D H:i:s string or a UTC timestamp for parsing via javascript.
Let's assume that +period+ is 86400 (The number of seconds in a day)
Let's assume that the timestamp is '2015-12-08 20:58:58'
From what I can see, it takes the timestamp, which internally is stored as an integer and divides by 86400.
'2015-12-08 20:58:58' / 86400 = 233231576.4566898000
It then uses the FLOOR operation which would make it 233231576 then multiplies by 86400 again (I assume that this is to ensure rounding to the day)
I end up with 20151208166400.
So that's the 8th December 2015 but I also have 166400 which I have no idea what it is?
So now the second part of the question is, how to convert this integer to 2015-12-08 %H:%i:%s or even a UTC timestamp for parsing via Javascript.
I mentioned the problem in the comment, but not a fix. The problem is that the proposed code is for a unix timestamp, not a datetime value.
This can be fixed by doing appropriate conversions
SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(MIN(timestamp)) / $period) * $period)
This gives you the flexibility of have arbitrary numbers of seconds for the groupings.
You're right that FLOOR(timestamp / 86400) * 86400 is a crude way of rounding a UNIX-style timestamp (seconds since 1970-01-01 00:00UTC) to midnight on the present day UTC.
If that's what you're trying to do, I suggest you try this kind of MySQL code:
SELECT DATE_FORMAT(DATE(`timestamp`), '%Y-%m-%d'),
...
GROUP BY DATE(`timestamp`)
This uses MySQL's built in date arithmetic to turn a timestamp into midnight.
But you should be careful of one thing. Those timestamps are all stored in UTC (f/k/a Greenwich Mean Time). When you do date arithmetic with them, or pull them out of the database to use them, they're automatically converted to local time according to your MySQL time zone settings.
It is rounding timestampt to period (e.g day).
DATE_FORMAT( DATE( FLOOR(MIN(timestamp)/"+period+")*"+period+" ) , '%Y-%m-%d %H:%i:%s' )
If period==day consider using only MySQL period rounding by DAY().
Convert a Date object to a string, according to universal time:
var d = new Date();
var n = d.toUTCString();
The result of n will be:
Mon, 28 Dec 2015 12:57:32 GMT

To calculate difference between two datetimes in mysql

I want the query to calculate the difference between two date time fields
to calculate total time taken
two date time fields are in same table
as start_time and stop_time
And I want to calculate total start duration and stop duration
You can use MySQL's UNIX_TIMESTAMP() function to convert your datetime expressions to seconds since the UNIX epoch, then taking the sum of all differences will yield the total duration in seconds:
SELECT SUM(UNIX_TIMESTAMP(stop_time) - UNIX_TIMESTAMP(start_time)) FROM my_table
See it on sqlfiddle.
Note that UNIX_TIMESTAMP() is limited to the range '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
HINT:
SELECT TIMESTAMPDIFF(SECOND,'2012-12-30 12:01:01','2012-12-31 10:02:00');
-- result: 79259 the difference in seconds with the time.
See this link for more details on DateTime functions.
Try this
SELECT TIMEDIFF(STOP_TIME - START_TIME) AS INTERVAL
FROM ......

How to convert timestamp to datetime in MySQL?

How to convert 1300464000 to 2011-03-18 16:00:00 in MySQL?
Use the FROM_UNIXTIME() function in MySQL
Remember that if you are using a framework that stores it in milliseconds (for example Java's timestamp) you have to divide by 1000 to obtain the right Unix time in seconds.
DATE_FORMAT(FROM_UNIXTIME(`orderdate`), '%Y-%m-%d %H:%i:%s') as "Date" FROM `orders`
This is the ultimate solution if the given date is in encoded format like 1300464000
To answer Janus Troelsen comment
Use UNIX_TIMESTAMP instead of TIMESTAMP
SELECT from_unixtime( UNIX_TIMESTAMP( "2011-12-01 22:01:23.048" ) )
The TIMESTAMP function returns a Date or a DateTime and not a timestamp, while UNIX_TIMESTAMP returns a unix timestamp
You can use
select from_unixtime(1300464000,"%Y-%m-%d %h %i %s") from table;
For in details description about
from_unixtime()
unix_timestamp()
SELECT from_unixtime( UNIX_TIMESTAMP(fild_with_timestamp) ) from "your_table"
This work for me

MySQL - return only entries from the past X days

I'm working with a database that has date information stored as a Unix timestamp ( int(11) ) and what I want to do is only return entries from the past X days, the past 90 days for example.
What I've come up with is:
SELECT * FROM mytable WHERE category=1 AND
FROM_UNIXTIME( time ) > DATE_SUB(now(), INTERVAL 91 DAY)
Where 'time' is the int(11) in the db. This seems to be working fine, but just wondering what others think of this.
SELECT * FROM mytable WHERE category=1 AND
time > (UNIX_TIMESTAMP() - ((60*60*24)*90))
or simply
SELECT * FROM mytable WHERE category=1 AND
time > (UNIX_TIMESTAMP() - (86400*90))
this is just comparing a number (seconds in this case)
This query is bound to cause you headaches down the way as MySQL needs to do the conversion of dates for every row making use of indexes impossible. Unix timestamps are numbers, so instead of converting a timestamp to another date format, convert your lookup dates to unix timestamps.
What is the reason for storing the timestamp as an int ? I would use the mysql DATETIME data type because you can use the many Date Time functions mysql has.
If you do not have control over the data type of this field I would convert your date to the unix timestamp int before you do your query and compare it that way.
Just thinking aloud... wouldn't doing it the other way around cause less work for the DB?
time > UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL 91 DAY) )