I need to retrieve all rows from a table where the created_at timestamp is during a certain hour ... say 04:00 and 05:00. Anyone know how to do this?
+1
A:
RecordNameHere.find_by_sql("SELECT * FROM `table_name_here` WHERE HOUR(created_at) = HOUR('4:01:00')")
The MySQL documentation is awesome: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_hour
Jamie Wong
2010-06-30 01:46:32
Cool! Was hoping for a tricky way, but that works. =)
james
2010-06-30 01:50:08
@james A tricky way? Tricky code doesn't impress, only annoys.
jfar
2010-06-30 03:23:59
+1
A:
For multiple hour range (eg: records between in 4:00 to 6:00)
User.all(:conditions => "HOUR(created_at) BETWEEN ? AND ?", 4, 5)
For single hour use the following syntax:
User.all(:conditions => "HOUR(created_at) = ?", 4)
Note 1
The HOUR
method returns the hour in 24 hour format. Provide the hour value accordingly.
KandadaBoggu
2010-06-30 02:27:35
Won't this grab all users who were created between `4:00:00` and `5:59:99`?
Jamie Wong
2010-06-30 03:05:28
Yes, for a single hour range user should use `=` operator rather than BETWEEN. I have updated my answer to reflect that.
KandadaBoggu
2010-06-30 04:58:24