# :find conditions using hour value of saved DateTime object

**URL:** <https://www.ruby-forum.com/t/find-conditions-using-hour-value-of-saved-datetime-object/150492>\
**Category:** Rails\
**Created:** [October 9, 2008, 3:45am UTC](https://www.ruby-forum.com/t/find-conditions-using-hour-value-of-saved-datetime-object/150492 "2008-10-09T03:45:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![david](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/aeb1de/32.png) [@david](https://www.ruby-forum.com/u/david)\
**Post date:** [October 9, 2008, 3:45am UTC](https://www.ruby-forum.com/t/find-conditions-using-hour-value-of-saved-datetime-object/150492/1 "2008-10-09T03:45:32Z")

</div>

I am wondering if it is possible to use a find condition to find  
objects according to the hour, ignoring the date. For example, i have  
a date field storing DateTime objects in the database and I want to  
find all objects where the hour is between the times 2:00PM and 4:00PM  
regardless of their date. It seems that to do this, ActiveRecord  
would have to perform an operation on each DateTime to find the hour,  
such as:

find(:all, :conditions =\> [“date.hour \>= ? AND date.hour \<= ?”,  
2:00PM, 4:00PM])

I know this does not work, but it helps to convey my goal. Maybe I  
have to write a raw SQL condition? Maybe it is easier to just save  
the time values in a separate field for each object in the database in  
the firstplace? I know saves are expensive and was trying to avoid  
them.

---

<div class="post-metadata">

**Author:** ![david](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/aeb1de/32.png) [@david](https://www.ruby-forum.com/u/david)\
**Post date:** [October 9, 2008, 3:52am UTC](https://www.ruby-forum.com/t/find-conditions-using-hour-value-of-saved-datetime-object/150492/2 "2008-10-09T03:52:35Z")

</div>

Ideally, you should save this in separate columns, as this query is  
definitely going to kill your database (there’s no way to make an  
index for it, the database will have to go through all rows), but you  
could do it like this if you’re using MySQL:

find(:all, :conditions =\> [“HOUR( date ) \>= ? AND HOUR( date ) \<= ?”, 2,  
4])

On Wed, Oct 8, 2008 at 10:44 PM, David [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> 2:00PM, 4:00PM])
> 
> I know this does not work, but it helps to convey my goal. Maybe I  
> have to write a raw SQL condition? Maybe it is easier to just save  
> the time values in a separate field for each object in the database in  
> the firstplace? I know saves are expensive and was trying to avoid  
> them.

–  
Maurício Linhares  
[http://alinhavado.wordpress.com/](http://alinhavado.wordpress.com/) (pt-br) | [http://blog.codevader.com/](http://blog.codevader.com/)  
(en)  
João Pessoa, PB, +55 83 8867-7208
