Use EXTRACT
and the UNIX-Timestamp
SELECT EXTRACT(EPOCH FROM TIMESTAMP '2011-05-17 10:40:28.876944') * 1000;
would give
1305621628876.94
Multiply it by 1000
to turn it into milliseconds. You can then convert it to whatever you want (decimal would be a good choice). Don't forget to keep the timezone in mind. JackPDouglas has such an example in his answer. Here is an excerpt from his answer (created
being the column with your timetamp) that illustrates how to work with timezones:
SELECT EXTRACT(EPOCH FROM created AT TIME ZONE 'UTC') FROM my_table;
There is a manual page on Time and Date functions.
The best way to compare date and time and get minutes back is probably to use one of the following:
SELECT TIME_TO_SEC(TIMEDIFF(timea,timeb)+0)/60
SELECT TIMESTAMPDIFF(MINUTE,timeb,timea)
Note that while TIMEDIFF
works with times, TIMESTAMPDIFF
requires a date component - and the values are switched around for TIMESTAMPDIFF
.
You can return hours with either of these:
SELECT TIME_TO_SEC(TIMEDIFF(timea,timeb)+0)/60/60
SELECT TIMESTAMPDIFF(HOUR,timeb,timea)
Note that when using DATEDIFF
, the value returned is a difference between the date components of the given time - thus, a value of 23:59 on one day compared to a value of 0:01 on the next (a 2 minute difference) results in a date difference of 1 (a full day).
To get a difference between two times in 24-hour periods (length of a day) first calculate the difference in minutes then divide by the proper values to find the number of 24-hour periods. Try this:
SELECT TRUNCATE(TIMESTAMPDIFF(MINUTE,timeb,timea)/60.0/24.0,0)
This truncates the decimal portion, returning only the number of complete 24-hour periods in the specified timespan.
Best Answer
Universal solution (for
datetime >= '2001-09-09 04:46:40'
- see comments).@time
variable contains unix timestamp (any accuracy). For example, when it is1556948248123
, it is normalized to1556948248.123
by the FROM_UNIXTIME's argument expression, and the result will be2015-11-13 19:08:01.123000
. The same result will be obtained when the variable is1556948248.123
or, for example,1.556948248123
.This variable is a placeholder - it can be fieldname or number literal.
You may create your own UDF if needed: