views:

33

answers:

2

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
Cool! Was hoping for a tricky way, but that works. =)
james
@james A tricky way? Tricky code doesn't impress, only annoys.
jfar
+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
Won't this grab all users who were created between `4:00:00` and `5:59:99`?
Jamie Wong
Yes, for a single hour range user should use `=` operator rather than BETWEEN. I have updated my answer to reflect that.
KandadaBoggu
Looking good! Thanks a bunch.
james