
Cheat sheet: Calendars and timeslices
Source:vignettes/articles/cheatsheet-timescales.Rmd
cheatsheet-timescales.RmdNested timeframes for a model year: build a calendar, place datetimes and data on it, recast between resolutions, draw it
PDF, A4, 2 pages · timescales 0.8.0 · 2026-11-29library(timescales)
cal <- calendar("m12_h24")
cal
Calendar: m12_h24 Timeframes (2): - MONTH (12) [token: m12] - HOUR (288) [token: h24, unit: 1 h] Leaf timeslices: 288 …
A calendar splits one model year into nested timeframes, coarsest first, under an implicit ANNUAL root. The members of a timeframe are its timeslices: m01 at MONTH, m01_h00 at HOUR, 24 per month. Members of the finest timeframe are the leaves, one row each of the leaftable:
head(calendar_leaftable(cal), 3)
MONTH HOUR share width weight total 1 m01 m01_h00 0.0001141553 1 31 0.003538813 2 m01 m01_h01 0.0001141553 1 31 0.003538813 3 m01 m01_h02 0.0001141553 1 31 0.003538813
autoplot(calendars$s4_hp3)One band per timeframe; each rectangle as long as the part of the year it stands for. DAY, PEAK, NIGHT are timeslices of HOUR 11, 4 and 9 hours wide (h06–h16, h17–h20, h21–h05).
share |
one unit of the timeframe, as a fraction of the year (an HOUR: 1/8760) |
width |
length on the time axis, in those units (default 1) |
weight |
times the timeslice repeats; 0 leaves it out |
total |
share × width × weight: the part of the year it stands for; sums to year_fraction
|
| timeslice | unit | width | weight |
dated hour (d365_h24) |
1 h | 1 | 1 |
average-day hour (WIN_h12, s4_h24) |
1 h | 1 | 90 |
hour block (WIN_DAY, s4_hp3) |
1 h | 11 | 90 |
weekday (MON, wd7) |
1 day | 1 | 52.14 |
month (m01, m12) |
31 days | 1 | 1 |
calendar_width(calendars$s4_hp3)[1:2, ]
HOUR unit_hours width weight hours 1 WIN_DAY 1 11 90 990 2 WIN_PEAK 1 4 90 360
calendar(name, ...) py_-joined tokens; ... passes year_start, utc_offset_minutes, year_fraction, desc.calendar_build(..., name, year_start, utc_offset_minutes, year_fraction) pyq <- calendar_build("q4", "h24")
calendar_timeslices(q)[1:3]
[1] "Q1_h00" "Q1_h01" "Q1_h02"
calendar_from_leaftable(leaftable, timeframes, members, name, layout, units, …) pyshare (optional width, weight); bare labels are composed into members.lt <- data.frame(
SEASON = rep(c("WIN", "SUM"), each = 2),
PART = rep(c("DAY", "NIGHT"), 2),
share = 0.25)
sn <- calendar_from_leaftable(lt,
c("SEASON", "PART"), name = "s2_p2")
calendar_timeslices(sn)
[1] "WIN_DAY" "WIN_NIGHT" "SUM_DAY" [4] "SUM_NIGHT"
calendar_leaftable(x) pyshare, width, weight, total.summary(cal): sizes, tokens, coverage, ranges of the lengths. names(cal) gives the timeframes, not the leaftable columns.
43 designs: calendars$<id> is pre-built and identical to calendar(id); calendar_catalog() gives id, timeframes, size, coverage class and regularity.
d365_h24 |
8760 | dated hours, no Feb 29 |
m12_h24 |
288 | an average day per month |
s4_h24 |
96 | an average day per season |
s4_hp3, q4_hp3
|
12 | day, peak, night blocks |
m12_md365 |
365 | month × day of month |
w52_h168 |
8736 | week × hour of the week |
wk2_h24 |
48 | workday, weekend × hour |
fy04_m12, … |
April-start fiscal years |
| complete | every instant has a timeslice (m12) |
| truncated | a stylised year drops instants (d365) |
| averaged | recurring periods merged (m12_h24) |
| sampled | a subset taken with filter_calendar()
|
calendar_timeslices(
calendar("fy04_m12"))[1:4]
[1] "m04" "m05" "m06" "m07"
Labels stay Gregorian (m04 is April); the member order and the anchored YEAR/YDAY move: fy04_* year 2021 runs 2021-04-01 to 2022-03-31. Any anchor: year_start = list(month = 7L, day = 1L). utc_offset_minutes = 330L: UTC + 5:30, constant offsets only.
register_calendar_token(name, timeframe, expand, alignment, unit) pyexpand() returns label and share (summing to 1).register_calendar_token("d4q", "YDAY",
function() data.frame(
label = paste0("Q", 1:4, "d"),
share = c(90, 91, 92, 92) / 365))
calendar_build("d4q", "h24")
Built in (list_calendar_tokens()): d360 d364 d365 d366 m12 m12a q4 s4 w52 w53 wd7 wk2 h24 h168 hp3 min60.
calendar_parents(x, timeframe, timeslice, target, token, …) pytarget) than those selected by name or by token label.calendar_parents(cal, "HOUR",
token = "h05")
[1] "m01" "m02" "m03" "m04" "m05" "m06" [7] "m07" "m08" "m09" "m10" "m11" "m12"
A token label (h05) names a member inside its parent. calendar_descendants(), calendar_ancestors(): every finer / coarser timeframe as data.frame(timeframe, timeslice); calendar_family(): adjacent parent–child pairs; calendar_ancestry(): all ancestor–descendant pairs.
calendar_next(x, timeframe, within, wrap) pywrap = FALSE.tail(calendar_next(cal,
within = "MONTH"), 1)
timeslice next_timeslice 288 m12_h23 m12_h00
calendar_share(x, timeframe, within) pytotal summed to a timeframe and normalised; per parent with within.calendar_id(calendar) py"<name>@<hash>" of the timeframes and members, as "m12_h24@c15c0ad6"; the hash is the same in R and Python.Calendar is an S7 class: cal@leaftable, @timeframes, @members, @meta.
filter_calendar(x, timeframe, timeslice, token) pycal["MONTH", "m01"] selects by name.two <- filter_calendar(
calendars$d365_h24,
"YDAY", c("d015", "d196"))
calendar_coverage(two)
total 0.005479452
calendar_source(calendar, record) pyprune_calendar(x, timeframe) py"ANNUAL" gives one timeslice.Coarse vs sampled. m12_h24 groups the year: each hour repeats on 28–31 days, totals sum to 1. Days filtered from d365_h24 keep dated hours (weight 1) and leave the rest out. Both hold HOUR; the weight tells them apart.
- No silent rule: a value column without
rule =or a registered rule stops the recast. -
d365has no Feb 29: in a leap year that day isNA, and a recast into it drops a grid point with a warning. -
filter_calendar()does not renormalise;calendar_share()gives normalised shares. -
weighted_meanandmeandiffer where declared shares differ from real time. - Fiscal calendars on calendar-year data: keep the fiscal window first, or January–March land on the slots of the year after.
- A wall needs
year =; without it the days fall back to a plain sequence.
datetime_to_timeslice(dtm, calendar, alignment) pyNA where not covered. Short form dtm2tsl().t <- as.POSIXct(c("2025-01-15 03:00",
"2025-07-20 18:00"), tz = "UTC")
dtm2tsl(t, calendars$s4_hp3)
[1] "WIN_NIGHT" "SUM_PEAK"
tsl2yday(tsl, calendar) pytsl2hour(c("m01_h00", "m04_h20"), cal)
[1] 0 20
as_timeframe(x, timeframe, format, …) py"MONTH", "WDAY", …); format = "token" gives "m04", "TUE".expand_calendar(x, year, by, tz, …) pynrow(expand_calendar(calendars$m12,
year = 2020, by = "day"))
[1] 366
base_calendar(years, by, tz) pydrop_feb29 |
Feb 29 → NA; Dec 31 stays d365
|
drop_last |
past the last label → NA (d360) |
repeat_last |
clamp to the last label (week 53 → w52) |
exact |
an error |
ALIGNMENT_RULES: tokens seed meta$alignment; alignment = overrides per call.
w <- merra2_cities[
merra2_cities$city == "Reykjavik", ]
w$timeslice <- dtm2tsl(w$datetime, cal)
w <- aggregate(W50M ~ timeslice, w, mean)
gg_calendar(cal, data = w, z = "W50M", year = 2019): each band holds the value recast to its timeframe.
recast_calendar(data, source, target, year, values, rule, by, na_action, parent, …) pyyear. Numeric columns are values (or name them in values); the rest ride along as identifiers.m <- data.frame(
timeslice = sprintf("m%02d", 1:12),
load = c(120, 118, 105, 92, 85, 88,
95, 100, 98, 90, 105, 122))
recast_calendar(m, calendars$m12,
calendars$q4, year = 2025,
rule = "weighted_mean")
timeslice load 1 Q1 114.21111 2 Q2 88.29670 3 Q3 97.66304 4 Q4 105.67391
recast_calendar(m, calendars$m12,
"ANNUAL", year = 2025, rule = "sum")
timeslice load 1 ANNUAL 1218
source (or "ANNUAL") as target aggregates within it.weighted_mean |
mean weighted by total: intensive (load, price) |
sum |
split down, sum up; totals conserved: extensive (energy) |
mean |
plain time-weighted mean over the grid |
copy |
the common value; an error if not constant |
sd |
spread over the grid; aggregation only |
share, logshare
|
each timeslice's share of its parent; keyed by source
|
na_action: grid points target does not cover are "drop"ped with a warning, kept as an NA row ("keep", totals conserved) or an "error".
join_calendar(data, calendar, key, timeframes, meta, tokens, …) py<name>.<TIMEFRAME> (timeframes =), <name>.token.<TIMEFRAME> (tokens = TRUE) and the lengths (meta = TRUE).d <- data.frame(timeslice =
c("m01_h00", "m07_h12"))
names(join_calendar(d, cal,
timeframes = "HOUR", tokens = TRUE))
[1] "timeslice" "m12_h24" [3] "m12_h24.HOUR" "m12_h24.token.HOUR"
- Key: a column named like the calendar, else
timeslice, elsedatetime. - Two calendars on one table are a crosswalk; existing columns are never overwritten.
- data.frame, tibble, data.table, dtplyr, arrow in; same class out; lazy inputs return the query unless
collect = TRUE.
recast_from_datetime(data, calendar, year, rule, by, na_action, …) pyrecast_calendar(): down to the datetime grid, up into a calendar.g <- recast_to_datetime(m,
calendars$m12, year = 2025,
rule = "sum", by = "day")
recast_from_datetime(g, calendars$q4,
rule = "sum", by = "day")
timeslice year load 1 Q1 2025 343 2 Q2 2025 265 3 Q3 2025 293 4 Q4 2025 317
calendar_map_between(source, target, year, by, …) pyn_from, n_overlap, weight w. calendar_map(): two timeframes of one calendar.register_calendar_map_between(source, target, map, …) pyregister_calendar_conversion(source, target, fun, …) pyget_*, list_*, clear_* companions: list_calendar_rules(), clear_calendar_rules(), list_calendar_maps(), clear_calendar_maps(), clear_calendar_conversions(). The generic recast() dispatches on the scale: recast_calendar() for a calendar, chaining with geoscales.
import pyarrow as pa
import timescales as ts
m12 = ts.calendar("m12")
q4 = ts.calendar("q4")
tsl = ts.calendar_timeslices(m12)
d = pa.table({"timeslice": tsl,
"energy": [float(i) for i in
range(1, 13)]})
ts.recast_calendar(d, m12, q4,
year=2021, rule="sum")
- Same names and argument order;
pymarks a line with a twin. - Data: pyarrow, pandas, polars, lazy Dataset or LazyFrame; results in the caller's type.
- Datetimes: pyarrow timestamps, or numpy, pandas, polars, Python datetimes.
-
summary(x)ists.calendar_summary(x),print(x)isstr(x);clear_*also takename. Figures stay in R.
hel <- merra2_cities[
merra2_cities$city == "Helsinki", ]
ggplot(hel) +
geom_calendar(calendar =
calendars$d365_h24, z = "W50M") +
scale_fill_viridis_c(option = "G") +
scale_x_discrete(
breaks = calendar_breaks(8)) +
scale_y_discrete(
breaks = calendar_breaks()) +
labs(x = NULL, y = NULL,
fill = "m/s") +
theme_calendar()
geom_calendar(calendar, z, datetime, by, x_tf, y_tf, fun, …)
geom_calendar_tile(calendar, z, timeslice, by, …)datetime or a timeslice column. Inputs are column names, not aes(); by = carries facet columns.gg_calendar(calendars$m12_md365,
type = "wall", data = hel,
z = "T10M", year = 2019) +
scale_fill_viridis_c(option = "C") +
labs(fill = "degC")
gg_calendar(object, type, data, z, year, rule, palette, labels, …)
calendar_layout(), calendar_wall_layout(), calendar_weekdays(): the plain data frames behind the figures. calendar_breaks() thins a dense axis.