Skip to main content

date_trunc and Group by Month in ActiveRecord

Group ActiveRecord counts by month, week or day with date_trunc, and handle time zones and empty months correctly.

R
Raza Hussain
· 7 min read · 12
A desk calendar listing Jan 2025 as 2, Feb 2025 as 0 in a red dashed box and Mar 2025 as 3, with a PST clock beside it.

In ActiveRecord you group by month with Signup.group(Arel.sql("date_trunc('month', created_at)")).count. It returns a hash with Time keys, one per month with rows. Two things go wrong in production. The month boundary follows UTC and not your users, and months with no rows are missing from the hash. Below are the fixes in plain Rails and what the groupdate gem does for you.

Tested on ActiveRecord 8.1.1, PostgreSQL 16.15, Ruby 3.3.6, groupdate 6.8.0 (installed in a throwaway gem directory). Everything here is PostgreSQL only. I did not test SQLite or MySQL, which need other functions.

The SQL you start with

SELECT date_trunc('month', created_at) AS month, COUNT(*)
FROM signups
GROUP BY 1
ORDER BY 1;

The test table has a created_at column of type timestamp(6) without time zone, the type Rails creates for t.datetime. Rails stores UTC in it. The app time zone is America/Los_Angeles. Six rows sit near month edges, and none fall in February UTC.

Plain date_trunc

Signup.group(Arel.sql("date_trunc('month', created_at)"))
      .order(Arel.sql("date_trunc('month', created_at)"))
      .count
SELECT COUNT(*) AS "count_all", date_trunc('month', created_at) AS "date_trunc_month_created_at"
FROM "signups"
GROUP BY date_trunc('month', created_at)
ORDER BY date_trunc('month', created_at)
2025-01-01 00:00:00 UTC (Time) => 2
2025-03-01 00:00:00 UTC (Time) => 3
2025-04-01 00:00:00 UTC (Time) => 1

Keys are Time objects in UTC. Order by the expression, not by 1. In a grouped count, Rails puts COUNT(*) first in the select list, so ORDER BY 1 sorts by the count. In my run it returned April, January, March, which is sorted by counts 1, 2, 3 and not by month.

The time zone trap

A signup at 2025-03-01 02:00 UTC happened on February 28 at 6 pm in Los Angeles. Plain date_trunc puts it in March. Your user, and your finance team, count it in February. The result above has no February at all.

Fix it by converting the stored value to local wall-clock time first. Because the column is timestamp without time zone, you need AT TIME ZONE twice. The first call tells PostgreSQL the value is UTC and returns a timestamptz. The second converts it to local time:

tz = Time.zone.tzinfo.name # "America/Los_Angeles"
expr = Signup.sanitize_sql_array(
  ["date_trunc('month', created_at AT TIME ZONE 'UTC' AT TIME ZONE ?)", tz]
)
Signup.group(Arel.sql(expr)).order(Arel.sql(expr)).count
2025-01-01 00:00:00 UTC (Time) => 2
2025-02-01 00:00:00 UTC (Time) => 1
2025-03-01 00:00:00 UTC (Time) => 3

February now exists, and the April 1 05:00 UTC signup moved back into March. sanitize_sql_array quotes the zone name. Take it from Time.zone.tzinfo.name and never from a raw param. An unknown zone name makes PostgreSQL raise an error.

Watch the keys. They print as UTC, but they are not UTC instants. They are local wall-clock values, and ActiveRecord labels them UTC because the column type has no zone. key.utc? returned true. Do not call in_time_zone on them. Format them as they are with key.strftime("%Y-%m") or convert with key.to_date.

The three-argument form

PostgreSQL 16 also accepts a zone as the third argument of date_trunc. It needs a timestamptz input:

"date_trunc('month', created_at AT TIME ZONE 'UTC', 'America/Los_Angeles')"

The keys are now real instants, each at local midnight:

2025-01-01 08:00:00 UTC => 2
2025-02-01 08:00:00 UTC => 1
2025-03-01 08:00:00 UTC => 3

key.in_time_zone gave 2025-02-01 00:00:00 -0800. I prefer this form when the key goes into a zone-aware chart. The two-AT TIME ZONE form is simpler when you only need labels. PostgreSQL 12 added it. The 12 release notes say “Allow date_trunc() to have an additional argument to control the time zone”, and the PostgreSQL 11 docs list only the two-argument forms. On PostgreSQL 11 or older, use the AT TIME ZONE form above.

Key types depend on the expression

Expression Key class in Ruby Example key
date_trunc('month', created_at) Time 2025-03-01 00:00:00 UTC
DATE(created_at) Date 2025-03-10
to_char(created_at, 'YYYY-MM') String "2025-03"

to_char keys sort as text, which works for YYYY-MM and breaks for formats such as Mon YYYY. Pick one key type for the app and convert at the query boundary.

Weeks start on Monday

date_trunc('week', created_at) returned Mondays in my test: 2025-01-13, 2025-01-27, 2025-02-24, 2025-03-10, 2025-03-17 and 2025-03-31. Date.beginning_of_week in the same Rails process returned :monday, so both agree. If your product counts weeks from Sunday, the SQL needs an explicit shift. I did not test one, so verify it on your own data.

Missing months

A month without rows is absent from the hash. A chart then draws a line from January straight to March. Fill the gaps in Ruby when the range is a few hundred buckets at most:

by_month = Signup.group(Arel.sql(expr)).count.transform_keys(&:to_date)
first, last = by_month.keys.minmax
months = []
d = first
while d <= last
  months << d
  d = d.next_month
end
months.index_with { |m| by_month.fetch(m, 0) }
# => {"2025-01-01"=>2, "2025-02-01"=>1, "2025-03-01"=>3}

The range endpoints come from the data, so a leading or trailing empty month is still invisible. Pass the range you want to show. A SQL-side fill with generate_series is the other option and is outside this post.

What groupdate does for you

The groupdate gem exists because the steps above repeat in every app. In the test it generated this SQL for the same table:

Signup.group_by_month(:created_at, time_zone: "America/Los_Angeles",
                      range: Time.utc(2025,1,1)..Time.utc(2025,4,30)).count
SELECT COUNT(*) AS "count_all",
  DATE_TRUNC('month', "signups"."created_at"::timestamptz AT TIME ZONE 'America/Los_Angeles')::date AS "..."
FROM "signups"
WHERE ("signups"."created_at" >= $1 AND "signups"."created_at" <= $2)
GROUP BY DATE_TRUNC('month', "signups"."created_at"::timestamptz AT TIME ZONE 'America/Los_Angeles')::date
Sun, 01 Dec 2024 (Date) => 0
Wed, 01 Jan 2025 (Date) => 2
Sat, 01 Feb 2025 (Date) => 1
Sat, 01 Mar 2025 (Date) => 3
Tue, 01 Apr 2025 (Date) => 0

You get Date keys, the zone handling, a range filter in SQL, and zero-filled buckets. Look at the first row. My UTC range started at 2025-01-01 00:00 UTC, which is December 31 in Los Angeles, so the gem added a December bucket. Ranges still need thought. Add the gem when you have more than two or three of these charts. For one report, the code above is shorter than the dependency.

Filter on the raw column

Grouping by an expression is fine. Filtering by one is not. With an index on created_at and 300,000 extra rows:

Signup.where(created_at: range)                          # index scan
Signup.where("date_trunc('month', created_at) = ?", t)   # sequential scan
Index Scan using index_signups_on_created_at on signups  (cost=0.42..22.42 rows=373 width=23)
Gather  (cost=1000.00..5708.11 rows=1500 width=23)
  ->  Parallel Seq Scan on signups  (cost=0.00..4558.11 rows=882 width=23)

These are planner estimates. The expression hides the column from the index. Use a range on created_at in where and keep date_trunc for the group only. The post on missing indexes covers the general case.

If you start from a SQL report with GROUP BY and HAVING, the converter gives the group call. Add the AT TIME ZONE expression yourself.

Related: GROUP BY and count in ActiveRecord, Database indexes existed, ActiveRecord ignored them, WHERE clause conditions in ActiveRecord

Frequently asked questions

How do I group by month in ActiveRecord without a gem?
Use group(Arel.sql("date_trunc('month', created_at)")).count. It returns a hash with Time keys in UTC for each month with rows.
Why are my monthly counts off for users in another time zone?
Rails stores UTC, so date_trunc on created_at cuts months at UTC midnight. In my test a signup at 2025-03-01 02:00 UTC fell in February in Los Angeles. Convert with AT TIME ZONE 'UTC' AT TIME ZONE 'America/Los_Angeles' before date_trunc.
Why does ORDER BY 1 sort my grouped count wrongly?
Rails puts COUNT(*) first in the select list of a grouped count, so ORDER BY 1 sorts by the count. Order by the date_trunc expression instead.
How do I show months with no rows?
The empty months are absent from the hash. Fill the gaps in Ruby by looping over the months you want and using fetch(month, 0), or use the groupdate gem, which returned zero-filled Date keys in my test.
Does date_trunc week start on Monday?
Yes. In my test date_trunc('week') returned Mondays, which matches the Rails default beginning_of_week of :monday.

Was this article helpful?

Your feedback helps us improve our content

Be the first to vote!

How We Verify Conversions

Every conversion shown on this site follows a strict verification process to ensure correctness:

  • Compare results on same dataset — We run both SQL and ActiveRecord against identical test data and verify results match
  • Check generated SQL with to_sql — We inspect the actual SQL Rails generates to catch semantic differences (INNER vs LEFT JOIN, WHERE vs ON, etc.)
  • Add regression tests for tricky cases — Edge cases like NOT EXISTS, anti-joins, and predicate placement are tested with multiple scenarios
  • Tested on Rails 8.1.1 — All conversions verified on current Rails version to ensure compatibility

Last updated: November 28, 2026

Try These Queries in Our Converter

See the SQL examples from this article converted to ActiveRecord—and compare the SQL Rails actually generates.

12

Leave a Response

Responses (0)

No responses yet

Be the first to share your thoughts

R

Raza Hussain

Full-stack developer specializing in Ruby on Rails, React, and modern JavaScript. 15+ years upgrading and maintaining production Rails apps. Led Rails 4/5 → 7 upgrades with 40% performance gains, migrated apps from Heroku to Render cutting costs by 35%, and built systems for StatusGator, CryptoZombies, and others. Available for Rails upgrades, performance work, and cloud migrations.

💼 15 years experience 📝 61 posts