Repository navigation
Recipe Time Buckets
Tier: Intermediate
Commands used: datefmt, timebucketp, search, pivotp
Anchor dataset: NYC 311 (1M-row sample, 2010–2020)
(30.0.0: dathere/qsv#5112.)
You have a million NYC 311 service requests and want them as a time series: requests per year, per day, a 7-day rolling average, and weekly counts per borough around the March 2020 lockdown.
timebucketp does the windowing. NYC 311 writes its timestamps as 04/18/2019 09:55:45 PM, month-first with a 12-hour clock, and timebucketp can't read that without help. So the first step is to normalize the dates with datefmt.
curl -L -o NYC_311_SR_2010-2020-sample-1M.7z \
https://raw.githubusercontent.com/wiki/dathere/qsv/files/NYC_311_SR_2010-2020-sample-1M.7z
7z x NYC_311_SR_2010-2020-sample-1M.7z # or 7zz; unpacks a 539 MB CSV
mv NYC_311_SR_2010-2020-sample-1M.csv nyc311.csvqsv slice -l 3 nyc311.csv | qsv select 'Created Date,Closed Date'Created Date,Closed Date
04/18/2019 09:55:45 PM,04/19/2019 03:45:24 AM
05/01/2010 09:59:44 AM,05/01/2010 10:24:07 AM
05/21/2020 06:15:38 PM,05/21/2020 06:33:51 PMtimebucketp can't parse these as they are:
qsv timebucketp -i 'Created Date' --every 1y nyc311.csv
# Could not parse the --index column as dates. Set its format with --date-format,
# e.g. --date-format %m/%d/%Y. (could not find an appropriate format to parse dates, ...)qsv datefmt 'Created Date,Closed Date' --formatstr '%Y-%m-%dT%H:%M:%S' \
nyc311.csv -o nyc311_iso.csv
qsv slice -l 3 nyc311_iso.csv | qsv select 'Created Date,Closed Date'Created Date,Closed Date
2019-04-18T21:55:45,2019-04-19T03:45:24
2010-05-01T09:59:44,2010-05-01T10:24:07
2020-05-21T18:15:38,2020-05-21T18:33:51datefmt recognizes the input format on its own and converts PM times to the 24-hour clock. Converting once has three benefits over passing a format to every later command:
-
No format string needed later.
timebucketpreads ISO dates with no--date-format, and ISO 8601 is the format other tools expect. -
Month-first vs. day-first stops mattering.
2019-04-18can only be read one way, soQSV_PREFER_DMYcan't change it. -
Text tools work on dates. ISO dates sort as text, and a regex like
^2020-selects a year (step 4).
Note
Why --formatstr. datefmt's default output is RFC 3339, and it drops a midnight time: 08/25/2010 12:00:00 AM becomes 2010-08-25, not 2010-08-25T00:00:00+00:00. This file has 148,049 midnight timestamps (step 5), so the default leaves a column that mixes dates and datetimes. timebucketp reads the date-only values as midnight, so the default output gives the same buckets. This recipe still passes --formatstr '%Y-%m-%dT%H:%M:%S', so every value is a plain local timestamp and a text search like T00:00:00$ (step 5) finds every midnight. --keep-zero-time also keeps the column uniform, in the default format (…T00:00:00+00:00).
The format above has no time-zone offset, on purpose. 311 timestamps are New York wall-clock time. datefmt reads and writes in UTC by default (--input-tz and --output-tz), so it never shifts the clock. Leaving the offset out means nobody mistakes these times for real UTC. If you need true UTC instants, convert with --input-tz America/New_York --output-tz UTC, and remember that the day and hour buckets then follow UTC.
qsv timebucketp -i 'Created Date' --every 1y nyc311_iso.csvCreated Date,count
2010-01-01 00:00:00,82625
2011-01-01 00:00:00,79256
2012-01-01 00:00:00,72547
2013-01-01 00:00:00,74961
2014-01-01 00:00:00,85467
2015-01-01 00:00:00,93458
2016-01-01 00:00:00,96884
2017-01-01 00:00:00,100807
2018-01-01 00:00:00,111785
2019-01-01 00:00:00,100206
2020-01-01 00:00:00,102004The default --agg is len, which is written as count. Each window is labeled with its start (--label left). The input doesn't have to be sorted: timebucketp sorts by the index itself.
Write one row per day. --fill-gaps makes sure a day with no requests appears with a count of 0 instead of being skipped:
qsv timebucketp -i 'Created Date' --every 1d --fill-gaps nyc311_iso.csv -o daily.csv
head -4 daily.csvCreated Date,count
2010-01-01 00:00:00,120
2010-01-02 00:00:00,145
2010-01-03 00:00:00,250Then run timebucketp again on its own output, in rolling mode. Each day gets the mean of the 7 days ending on it:
QSV_POLARS_FLOAT_PRECISION=1 qsv timebucketp -i 'Created Date' \
--rolling --period 7d --agg mean:count daily.csv | qsv slice -l 8Created Date,count_mean
2010-01-01 00:00:00,120.0
2010-01-02 00:00:00,132.5
2010-01-03 00:00:00,171.7
2010-01-04 00:00:00,230.0
2010-01-05 00:00:00,252.8
2010-01-06 00:00:00,257.7
2010-01-07 00:00:00,265.4
2010-01-08 00:00:00,282.9The first six rows average fewer than 7 days because there's nothing before 2010-01-01. Drop them if a partial window would mislead. --fill-gaps matters here: the rolling window is measured in time, but a day missing from daily.csv would leave that day's 0 out of the mean. QSV_POLARS_FLOAT_PRECISION only rounds the output.
Rolling directly over nyc311_iso.csv would give one row per request (1M rows). Rolling over the daily table gives one row per day.
ISO dates let a plain regex select the year:
qsv search -s 'Created Date' '^2020-' nyc311_iso.csv -o nyc311_2020.csv
qsv timebucketp -i 'Created Date' --every 1w --start-by monday --by Borough \
nyc311_2020.csv -o weekly_borough.csv
head -3 weekly_borough.csvBorough,Created Date,count
BRONX,2019-12-30 00:00:00,173
BRONX,2020-01-06 00:00:00,287The output is in long form, with one row per borough and week. Widen it with pivotp, with each borough as a column:
qsv pivotp Borough --index 'Created Date' --values count --agg first \
weekly_borough.csv -o weekly_wide.csv
qsv slice -s 8 -l 8 weekly_wide.csvCreated Date,BRONX,BROOKLYN,MANHATTAN,QUEENS,STATEN ISLAND,Unspecified
2020-02-24 00:00:00,257,452,304,348,58,2
2020-03-02 00:00:00,311,497,351,365,71,10
2020-03-09 00:00:00,342,465,353,375,76,8
2020-03-16 00:00:00,290,409,299,329,59,4
2020-03-23 00:00:00,278,349,258,249,33,5
2020-03-30 00:00:00,247,371,268,246,47,11
2020-04-06 00:00:00,297,382,301,254,47,14
2020-04-13 00:00:00,300,409,314,277,61,20New York's stay-at-home order took effect on March 22, 2020. Every borough falls from the week of March 9 to the week of March 23, Queens from 375 to 249 and Staten Island from 76 to 33.
The first and last weeks are partial. The week labeled 2019-12-30 starts on a Monday but holds only January 1–5, because the input was cut at the year boundary. The sample itself ends partway through December 23, 2020 (tail -2 daily.csv shows just 6 requests that day), so the week of 2020-12-21 is short too. Treat both ends as incomplete.
Before using hourly or 15-minute windows, count the timestamps that are exactly midnight:
qsv search -s 'Created Date' 'T00:00:00$' nyc311_iso.csv -o midnight.csv
qsv timebucketp -i 'Created Date' --every 1y midnight.csv
qsv frequency -s Agency --limit 2 midnight.csvCreated Date,count
2010-01-01 00:00:00,28026
2011-01-01 00:00:00,27378
2012-01-01 00:00:00,23796
2013-01-01 00:00:00,24426
2014-01-01 00:00:00,25677
2015-01-01 00:00:00,13367
2016-01-01 00:00:00,1629
2017-01-01 00:00:00,1736
2018-01-01 00:00:00,1503
2019-01-01 00:00:00,402
2020-01-01 00:00:00,109
field,value,count,percentage,rank
Agency,HPD,136579,92.25257,1
Agency,DOHMH,11158,7.53669,2
Agency,Other (4),312,0.21074,0There are 148,049 of them, and 92% come from HPD. In 2010–2014 they are about a third of each year's requests (30–35%), in 2015 about 14%, and from 2016 on 2% or less. They look like dates with no time of day. In hourly windows they pile into the 00:00 bucket:
qsv search -s 'Created Date' '^2012-01-10' nyc311_iso.csv -o jan10.csv
qsv timebucketp -i 'Created Date' --every 1h jan10.csv | qsv slice -l 3
# Created Date,count
# 2012-01-10 00:00:00,100
# 2012-01-10 01:00:00,2
# 2012-01-10 02:00:00,1
# without the midnight rows (timebucketp reads files, not stdin)
qsv search -s 'Created Date' -v 'T00:00:00$' jan10.csv -o jan10_timed.csv
qsv timebucketp -i 'Created Date' --every 1h jan10_timed.csv | qsv slice -l 3
# Created Date,count
# 2012-01-10 00:00:00,2
# 2012-01-10 01:00:00,2
# 2012-01-10 02:00:00,1Daily and coarser buckets aren't affected. For sub-daily work, exclude the midnight rows as shown, or bucket the agencies that record real times separately.
If you only need timebucketp, --date-format reads the raw column directly. The daily table comes out byte-identical to the one from step 3:
qsv timebucketp -i 'Created Date' --every 1d \
--date-format '%m/%d/%Y %I:%M:%S %p' nyc311.csv -o daily_raw.csv
cmp daily.csv daily_raw.csv && echo identical
# identicalThis skips a pass over the file, but every later command needs the same format string, and text filters like ^2020- won't work on the raw dates.
28,619 requests have no Closed Date, and an empty index value is an error:
qsv timebucketp -i 'Closed Date' --every 1y nyc311_iso.csv
# The --index column has empty values. Remove those rows first, e.g. with
# `qsv search --select <index> --invert-match '^$'`. ...
qsv search -s 'Closed Date' -v '^$' nyc311_iso.csv -o closed.csv
qsv timebucketp -i 'Closed Date' --every 1y closed.csv | qsv slice -l 4
# Closed Date,count
# 1900-01-01 00:00:00,224
# 2009-01-01 00:00:00,5
# 2010-01-01 00:00:00,76589
# 2011-01-01 00:00:00,74417The 1900 bucket is 224 placeholder close dates. A yearly bucket is a quick way to find such outliers.
-
--every 15m, or--every 1h --offset -30mfor windows on the half hour. -
--every 1d --period 7dfor overlapping windows that start each day and span a week. -
--aggwith several functions, e.g.--agg len,first:Agency.
See SQL & Polars → timebucketp for the window, rolling and aggregation options.
-
datefmtis one streaming pass over the file. It runs in parallel (--jobs,--batch). Converting once saves re-parsing text dates in every later command. -
timebucketploads its input into memory (🤯) and sorts by the index. Use--sortedwhen the input is already in order. - Like the other Polars commands,
timebucketpuses a<file>.pschema.jsonfromschema --polarswhen one exists. Make the schema fornyc311_iso.csv, afterdatefmt, not for the raw file.
- SQL & Polars → timebucketp: the full option walkthrough
- Transform & Reshape → datefmt
-
Recipe: Date Enrichment: more
datefmton NYC 311 -
Recipe: Group By:
pivotpandsqlpgroup-bys -
docs/help/timebucketp.mdanddocs/help/datefmt.md
qsv — GitHub · Releases · Discussions · crates.io · qsv pro · Try it online · Benchmarks · DeepWiki · DOI · Licensed MIT · Third-party notices · AI Policy
qsv was made possible by datHere: standards-based, best-of-breed, open source solutions to make your Data Useful, Usable & Used.
Edit this page: Contributing to the Wiki
Home · Why qsv? · Tier legend
- Whirlwind Tour · Notebooks · Lessons & Exercises
- Benchmarks · Interactive Benchmarks
- Visualizations Gallery
- Neuro-symbolic, Localizable, Data Schematics
- Feature Flags · Goals/Non-goals · Testing
- Talks: NYC SOD 2022 · csv,conf,v8 · PyCon US 2025 · csv,conf,v9 · NYC SOD 2026
- "Have we achieved ACI?" series: 1 · 2 · 3 · 4
- Sponsor
- All Commands (index)
- Selection & Inspection
- Transform & Reshape
- Aggregation & Statistics
- Joins & Set Ops
- SQL & Polars
- Validation & Schema
- Metadata Profiling (profile)
- Conversion & I/O
- Geospatial
- Visualization (viz)
- HTTP & Web
- Get & Disk Cache
- Scripting (Luau / Python)
- Indexing, Compression & Diff
- AI & Documentation
- Recipes index
- Inspect an Unknown CSV
- Clean & Normalize
- Geographic Enrichment
- Date Enrichment
- CKAN Integration
- DCAT-US v3 for data.gov
- JSON Schema Validation
- Round-Trip SAS / Stata / SPSS
- Build a Data Pipeline
- Stats → Insights
- Data-Quality Signals with moarstats
- Group By
- Time Buckets
- Fetch & Cache
- Larger-than-RAM CSV
- Diff & Audit
- Multi-table Joins
- Synthesize Fake Data
- Performance Tuning
- Benchmarks
- Tuned csv Fork Benchmarks
- Security & Dependency Audits
- Environment Variables
- Stats Cache & Caching
- Lookup Tables
- MiniJinja Templating