Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

epoch time and MySQL query

Tags:

mysql

epoch

I have a table like this:

id   | date
---- | -----------
1    | 1319043263
2    | 1319043578

which date field format is in epoch. I have to group every row that belongs to same day and show them in a separate group. How can I do that in MySQL?

Thanks.

like image 620
silvercover Avatar asked Oct 19 '11 17:10

silvercover


People also ask

How do I get epoch in MySQL?

MySQL - UNIX_TIMESTAMP() Function Where a time stamp is a numerical value representing the number of milliseconds from '1970-01-01 00:00:01' UTC (epoch) to the specified time.

Does MySQL support timestamp?

MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.

How do you calculate epoch time?

POSIX defines that you can deduce the number of days since The Epoch (1970-01-01 00:00:00Z) by dividing the timestamp by 86400. This deliberately and consciously ignores leap seconds.

How do you convert epoch time to human readable?

Convert from epoch to human-readable datemyString := DateTimeToStr(UnixToDateTime(Epoch)); Where Epoch is a signed integer. Replace 1526357743 with epoch. =(A1 / 86400) + 25569 Format the result cell for date/time, the result will be in GMT time (A1 is the cell with the epoch number).


1 Answers

Group By:

SELECT COUNT(`id`) AS `Records`, DATE(FROM_UNIXTIME(`date`)) AS `Date` 
FROM `table`
GROUP BY DATE(FROM_UNIXTIME(`date`))

Output:

    Records | Date
--------------------------------
      10    | 2011-10-19
      10    | 2011-10-18

Order By:

SELECT `id`, FROM_UNIXTIME(`date`) AS `Date`
FROM `table`
ORDER BY DATE(FROM_UNIXTIME(`date`)) [ASC|DESC]

(Though in actuality you would get the same ordering using only FROM_UNIXTIME() or the raw date value since they would all stack properly in an ordering attempt)

Output:

      id    | Date
--------------------------------
      03    | 2011-10-19 12:00:00
      02    | 2011-10-18 12:00:00
      01    | 2011-10-17 12:00:00

This converts the unix timestamp into a mysql datetime and then extracts the date value from that which is applied to the grouping or order clause

If you want to group by day regardless of month and year use DAY() instead of DATE()

However could you expand on the part about "group each row by day". what result do you want to show? when you group on something you use some sort of aggregate processor like COUNT() or SUM() on a field within the group.

MySQL Group Functions Reference

MySQL Date & Time Function Reference

like image 158
JoshHetland Avatar answered Oct 16 '22 17:10

JoshHetland