Epoch Date Conversion to SQL Server - sql-server-2008

Good Day,
I have a question. What type of epoch date's are these and how would I convert them into a SQL Server datetime format.
37564691530
37564704499
37564708633
37564721033
37564743361
37564746236
I have googled for 2 days and cant find anything except this formula which gives me an arithmetic overflow message when i try to convert it.
select
DATEADD(ss, 37564691530 - 3600 * 5, CONVERT(DATETIME, '1900-01-01 00:00:00', 102))
Any help would really be appreciated.

13 digit epoch represent total milliseconds 10 digit epoch represent total seconds. You have first one - milliseconds.
And sql DateAdd function accept second parameter(Increment) as Integer. You try to pass a bigint value. Thats why throw Arithmetic overflow error.
try this
DECLARE #MS BIGINT
SET #MS = 37564746236
select DATEADD(SECOND, #MS / 1000, '1970-01-01')

Related

MySQL UNIX_TIMESTAMP(now()) - current time in milliseconds

Is there a MySQL way to query based on current MySQL time in milliseconds?
I'm trying:
SELECT UNIX_TIMESTAMP(), UNIX_TIMESTAMP(NOW()) as now_in_mili
but both columns return the same (the 1970 epoch time).
I'm expecting 'now_in_mili' to print current date in milliseconds such as
it is possible in JavaScript:
Date.parse(new Date())
You need to pass an argument to the NOW() function to specify how many digits of fractional seconds you want it to include. It supports microseconds, but if you want milliseconds you can just use NOW(3) and then multiply the result by 1000, like this:
SELECT UNIX_TIMESTAMP(NOW(3))*1000 as now_in_mili

Error Code: 1292. Truncated incorrect time value

SELECT *
FROM SESSIONS
WHERE TIME_TO_SEC(TIMEDIFF(NOW(), SESSION_CREATED)) / 3600 >= 24
This give me 2 results
DELETE FROM SESSIONS
WHERE TIME_TO_SEC(TIMEDIFF(NOW(), SESSION_CREATED)) / 3600 >= 24
And this give me: "Error Code: 1292. Truncated incorrect time value"
SESSION_CREATED is TIMESTAMP Datatype
Actual data:
SESSION_ID SESSION_CREATED
223133 2017-05-22 07:14:34
223134 2017-05-22 07:14:36
How can the select work but not the delete?
Why are you using such a complicated expression? Why not just do:
DELETE FROM SESSIONS
WHERE SESSION_CREATED < NOW() - INTERVAL 1 DAY;
As for why your code might fail, it is using timediff() which is limited to the range of the time data type. And this is:
MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or
'HHH:MM:SS' format for large hours values). TIME values may range from
'-838:59:59' to '838:59:59'.
Because you are using NOW(), the values change from one iteration to the next. You just happened to run the SELECT when the data wasn't too old and then the DELETE when it was.
Example for Timediff using TIMESTAMPDIFF on MySQL:
To use TIMESTAMPDIFF, define the unit (SECOND, MINUTE, HOUR...), the initial and end date (must be timestamp's datatype).
ROUND( TIMESTAMPDIFF(HOUR, initial_date, CURRENT_TIMESTAMP()) / 24, 2 )

Redshift - Convert epoch string to timestamp

I have got a table with 2 columns epoch_start and epoch_end.
I want to find the difference in days of these 2 epochs.
The problem i am facing is that the above columns are character varying(5000) type.
The query im running is
select datediff(day,'1459762341','1450762341') as numdays;
The error i get is
ERROR: invalid input syntax for type timestamp: "1459762341"
I have found the solution -
To get timestamp from epoch -
SELECT (TIMESTAMP 'epoch' + '1459762341' * INTERVAL '1 Second ') as
mytimestamp
For datediff between two epochs -
select datediff(day,(TIMESTAMP 'epoch' + '1458762341' * INTERVAL '1 Second '), (TIMESTAMP 'epoch' + '1459762341' * INTERVAL '1 Second ')) as numdays;
"epoc" time is just the number of seconds from 1/1/1970, so its just some counter of the number of seconds from that date.
So, epic_start can really be thought of as start_seconds, and epic_end is really just end_seconds.
The fact that they are the count of the number of seconds from the same starting point is the only thing that really matters.
To get the number of days between two numbers representing seconds from the same starting point:
days = (end_seconds - start_seconds)/60/60/24
or
SELECT (end_seconds - epic_start)/60/60/24 AS numdays
Redshift will return an integer value without the decimal portion, so if the formula returns 1.9, numdays will be 1.
You are passing wrong parameters in datediff().
SELECT DATEDIFF('2014-11-30','2014-11-29') AS DiffDate
Above will return the difference in days between two given dates.
Read more on datediff() here datediff

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

MYSQL - datetime to seconds

I wasn't able to find out (googling, reading mysql reference manual) how to get value of DATETIME in seconds in MySQL.
I dont mean to extract seconds from datetime, but to convert it into seconds.
If by "convert to seconds", you mean "convert to an UNIX Timestamp" (i.e. number of seconds since 1970-01-01), then you can use the UNIX_TIMESTAMP function :
select UNIX_TIMESTAMP(your_datetime_field)
from your_table
where ...
And, for the sake of completness, to convert from an Unix Timestamp to a datetime, you can use the FROM_UNIXTIME function.
If you want to have the difference between two DATETIME values, use TIMESTAMPDIFF:
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument. The legal values for unit are the same as those listed in the description of the TIMESTAMPADD() function.
mysql> SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
-> 3
mysql> SELECT TIMESTAMPDIFF(YEAR,'2002-05-01','2001-01-01');
-> -1
mysql> SELECT TIMESTAMPDIFF(MINUTE,'2003-02-01','2003-05-01 12:05:55');
-> 128885
unit can also be HOUR which is what you asked for in one of the comments.
The unit argument can be any of the following:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
The level of usefulness of some of the other options will of course be determined by the granularity of the data. For instance, "MICROSECOND" will only have limited use if you are not storing microseconds in your DATETIME values.
Use TIME_TO_SEC in previous versions for mysql
SELECT TIME_TO_SEC(time column) FROM table
i used in mysql
TO_SECONDS(your date goes here) method to convert date to seconds from year 0
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
The function UNIX_TIMESTAMP(datetime) returns the unix time, which happens to be the number of seconds since 1-Jan-1970 0000 UTC. That may be what you need, but not if you're dealing with dates of birth, historical dates, or dates after 2037.
Starting in mysql 5.5.0 you can use to_seconds()
TO_SECONDS(FIELD_NAME)
FIELD_NAME must be DATETIME type
I have created my own query for your problem:
SELECT HOUR(`colname`) * 3600 + MINUTE(`colname`) * 60 + SECOND(`colname`)
FROM widgets
WHERE id = 1;
Use id = 1 if you have to take a specific row.
The output will be in seconds.