How can I group on the created_at field and return only the Date and hour - ruby

I run the following in Rails:
coe = trackers.where(:trackable_type => "Mailing").count(:group => 'DATE(created_at)')
which returns a hash with the items nicely grouped.
However I want to group not by date only by date but by the hour, but not the minutes or seconds.
How can I run this query so all the heavy lifting is done by Postgresql and not convert after I get the data set back?
My mistake I want to group by Date and Hour. Sorry for the confusion.

It sounds like you want the date_trunc() function:
http://www.postgresql.org/docs/current/interactive/functions-datetime.html#FUNCTIONS-DATETIME-TABLE

I want to group not by date but by the hour, but not the minutes or
seconds.
Bold emphasis mine.
So date_trunc()is probably not what you want, but EXTRACT or date_part():
coe = trackers.where(:trackable_type => "Mailing").count(:group => 'EXTRACT (hour FROM created_at)')

Related

Laravel/PHP/Carbon parse a date to one and three days from now() to the hour, disregarding minutes and seconds

I'm using Laravel 5.4 and Carbon to find dates that are exactly one day and three days prior to a laravel job (to the hour) to send notifications. So for example if the date was 2019-03-10 18:00:03 or 2019-03-10 18:15:34, I'd like to send a notification tomorrow at 2019-03-07 18:00:00 and another at 2019-03-09 18:00:00. I'd like to do this in an eloquent query, but not really sure how to "lazy match" by day and hour. If I have an Appointment model with a start_date timestamp, I know I can do exact matches by day or date, but I want to find matches that disregard the hours/seconds. I was considering something along these lines:
$oneDayAppointments = Appointment::whereDay(
'start_date',
Carbon::now()->addDay()->day
)->get();
...would get me any appointments where the start_date is a day from now. Now how would I hone it to the day and hour. If I were to just use a where clause:
$oneDayAppointments = Appointment::where(
'start_date',
Carbon::now()->addHours(24)
)->get();
...I could get exact matches, but only if the minutes/seconds were a match as well. Thanks!
Working on my comment above, this should do it
$tomorrowStart = Carbon::createFromFormat('Y-m-d H:i:s', Carbon::now()->addDay()->format('Y-m-d H:00:00'));
$tomorrowEnd = $tomorrowStart->copy()->addHour()->subSecond();
//whereBetween('start_date', [$tomorrowStart, $tomorrowEnd])
https://laravel.com/docs/5.8/queries

Retrieve database records between two weekdays

I have several records in my database, the table has a column named "weekday" where I store a weekday like "mon" or "fri". Now from the frontend when a user does search the parameters posted to the server are startday and endDay.
Now I would like to retrieve all records between startDay and endDay. We can assume startDay is "mon" and endDay is "sun". I do not currently know how to do this.
Create another table with the names of the days and their corresponding number. Then you'd just need to join up your current table with the days table by name, and then use the numbers in that table to do your queries.
Not exactly practical, but it is possible to convert sun,mon,tue to numbers using MySQL.
Setup a static year and week number like 201610 for the 10th week of this year, then use a combination of DATE_FORMAT with STR_TO_DATE:
DATE_FORMAT(STR_TO_DATE('201610 mon', '%X%V %a'), '%w')
DATE_FORMAT(STR_TO_DATE('201610 sun', '%X%V %a'), '%w')
DATE_FORMAT(STR_TO_DATE('201610 tue', '%X%V %a'), '%w')
These 3 statements will evaluate to 0,1,2 respectively.
The main thing this is doing is converting the %a format (Sun-Sat) to the %w format (0-6)
well i don't know the architecture of your application as i think storing and querying a week day string is not appropriate, but i can tell you a work around this.
make a helper function which return you an array of weekdays in the range i-e
function getWeekDaysArray($startWeekDay, $endWeekDay) {
returns $daysArray['mon','tue','wed'];
}
$daysRangeArray = getWeekDaysArray('mon', 'wed');
now with this array you can query in table
DB::table('TableName')->whereIn('week_day', $daysRangeArray)->get();
Hope this help

Ruby on Rails 3 convert time to DateTime in specific timezone

I have column which stores only time. I want to convert to it into datetime and then to a specific timezone. When I do it on console using only the attribute, it shows correct conversion value. But when I use it in query the query shows the current time in UTC. Suppose I have time "05:15" stored in Central time. Now when I want to fetch records for a interval of 30 minutes plus and minus of this time, I do following,
day = Time.now
# departure_time_from _db below is the name of column in table which store time
departure = departure_time_from _db.change(:day => date.day, :month => date.month, :year => date.year)
departure = departure.in_time_zone("Central Time (US & Canada)")
When I execute above code on console and see the value, it shows correct converted value. But when I use this variable in below query, current time gets used instead of the departure time.
Model.where("column_name > ? and "column_name < ?, departure - 30.minutes, departure + 30.minutes)
The time used in above query should be the time I want i.e Central time zone, but in query output, it shows UTC being used.
Please let me know what i am missing.
It shouldn't matter what time zone the query uses in the where clause as long as it's the same time representation. The time you're seeing in your query output from Rails is most likely the UTC equivalent of the ruby DateTime object being passed to the where statement. So if departure is 12:00 noon (UTC -6) in your Ruby code then the time shown in the SQL query will be 18:00, which corresponds to noon CST.

ActiveRecord count of distinct days from created_at?

Is it possible to retrieve a count of distinct records based on a field value if the field needs to be interrogated (ideally, using ActiveRecord alone)?
For example, the following returns a count of unique records based on the 'created_at' field:
Record.count('created_at', :distinct => true)
However, is it possible to get a count of, say, unique days based on the 'created_at' field in a similar way?
A naive ActiveRecord example to explain my intent being:
Record.count('created_at'.day, :distinct => true)
(I know the string 'created_at' isn't a 'Time', but that's the sort of query I'd like to ask ActiveRecord.)
You need to group the records. For example
Record.group('DATE(created_at)').count('created_at')
tells you the number of rows created on each particular date, or
Record.group('DAYOFWEEK(created_at)').count('created_at')
would tell you the number of rows created on individual days of the week.
Beware that this with the usual active record setup this will do date calculations in UTC, if you want to do your calculations in a specific timezone you'll have to add that conversion to the group statement.

Determine the amount of clicks required to reach a specific date using a JQuery calendar?

I have a jquery calendar for the start date of a project.
Using Watir (automated browser driver, a gem for ruby), I have a set date that I would like to enter in.
The calendar start date is always today's date, whatever that may be for the day it is used. I was wondering if there was a way that ruby can process what today's date is, and use the specified date provided by the user, to calculate the difference of months between them.
Here is an example of the Calendar plugin: http://jqueryui.com/datepicker/
example:
today's date is 30/10/2012, if there was a project that were to start on the 20/12/2012, that would be 2 months from now, so 2 clicks on the next month button.
Is there a way I could do this?
Here is how I approached a similar situation with JSdatepicker:
$today = Time.now.strftime("%e").gsub(" ", "") #one digit day of month without leading space
#browser.text_field(:id => /dateAvailable/).click
Watir::Wait.until(60) {#browser.div(:id => /dateAvailable_popup_cal/).td(:text => $today).exists?}
#browser.div(:id => /dateAvailable_popup_cal/).td(:text => $today).click
Set or grab the date.
Click the text_field that fires the JSDatePicker object
Wait until the calendar actually pops up
The current month is shown, so choose today's date number.
In your case, you also need to set the month. Whether prompting the user for this, or choosing "today", the theory is the same:
$month = Date::MONTHNAMES[Date.today.month] #etc
Pseudo-code making lots of assumptions (only future dates, month name shown on calendar as text, etc):
while !#jquerytablewindow.text.include?($month)
next_month_button.click
end
I don't see a specific advantage to my method versus counting each month, unless of course we add a month to the calendar one day and you still want your code to work!
You could do:
#End date converted to date object
specified_date = '20/12/2012'
end_date = Date.parse(specified_date)
#Start date (today - 30/10/2012)
today = Date.today
#Determine difference in months
number_of_months_up_to_today = (today.month + today.year * 12)
number_of_months_up_to_end = (end_date.month + end_date.year * 12)
clicks_required = number_of_months_up_to_end - number_of_months_up_to_today
#=> 2
Basically it is counting the number of months since the year 0 and then finding the difference.

Resources