Skip to contents

Nested 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-29
A calendar
library(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)
Icicle of the s4_hp3 calendar, ANNUAL over four seasons over day, peak and night blocks

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, width, weight
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
Build
calendar(name, ...) py
A catalog design by id, or any _-joined tokens; ... passes year_start, utc_offset_minutes, year_fraction, desc.
calendar_build(..., name, year_start, utc_offset_minutes, year_fraction) py
Tokens coarsest first; the Cartesian product of their labels is the leaftable.
q <- 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, …) py
Any table of leaves with share (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"
Inspect
calendar_timeframes(x, finest) py
Timeframe names, coarsest first; calendar_rank() gives a position.
calendar_timeslices(x, timeframe) py
The members of a timeframe, in order; without one, the leaves.
calendar_leaftable(x) py
One row per leaf: a member column per timeframe, share, width, weight, total.
calendar_width(x) py
Unit, width and weight of the leaf timeslices, in hours

summary(cal): sizes, tokens, coverage, ranges of the lengths. names(cal) gives the timeframes, not the leaftable columns.

The catalog

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()
Year start, offset, tokens
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) py
A custom token: expand() 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.

Navigate
calendar_children(x, timeframe, timeslice, target, token, …) py
calendar_parents(x, timeframe, timeslice, target, token, …) py
Members one step finer / coarser (or at target) 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) py
The successor of each timeslice, for storage levels and ramps; a cycle unless wrap = FALSE.
tail(calendar_next(cal,
  within = "MONTH"), 1)
    timeslice next_timeslice
288   m12_h23        m12_h00
calendar_share(x, timeframe, within) py
total summed to a timeframe and normalised; per parent with within.
Identity
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_tree(calendar) py
The parts, each marked fixed, derived or mutable.
upgrade_calendar(calendar) py
Bring a Calendar to the current form

Calendar is an S7 class: cal@leaftable, @timeframes, @members, @meta.

Subsets and samples
filter_calendar(x, timeframe, timeslice, token) py
Keep the leaves under selected members; nothing renormalised. cal["MONTH", "m01"] selects by name.
two <- filter_calendar(
  calendars$d365_h24,
  "YDAY", c("d015", "d196"))
calendar_coverage(two)
      total 
0.005479452 
calendar_coverage(x, weight) py
Coverage of a sampled Calendar
calendar_source(calendar, record) py
The calendar a subset was taken from: rebuilt from the catalog, or kept in the record.
prune_calendar(x, timeframe) py
Cut the hierarchy at a timeframe: leaves merge, totals sum. "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.

Pitfalls
  • No silent rule: a value column without rule = or a registered rule stops the recast.
  • d365 has no Feb 29: in a leap year that day is NA, and a recast into it drops a grid point with a warning.
  • filter_calendar() does not renormalise; calendar_share() gives normalised shares.
  • weighted_mean and mean differ 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.
Datetimes and timeslices
datetime_to_timeslice(dtm, calendar, alignment) py
The leaf each instant falls in; NA 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" 
tsl2dtm(tsl, calendar, year, tz, …) py
The instant each timeslice starts at.
tsl2hour(tsl, calendar) py
tsl2month(tsl, calendar, year) py
tsl2yday(tsl, calendar) py
Hour of the day, month, day of the year: integers, read through the calendar, never parsed.
tsl2hour(c("m01_h00", "m04_h20"), cal)
[1]  0 20
hour2HOUR(x, calendar) py
yday2YDAY(x, calendar) py
Back to labels: h05, d032; on an hp3 calendar the block an hour falls in.
as_timeframe(x, timeframe, format, …) py
One component of a datetime ("MONTH", "WDAY", …); format = "token" gives "m04", "TUE".
Grids and alignment
expand_calendar(x, year, by, tz, …) py
The grid of a model year, each point with its timeslice; leap- and fiscal-aware.
nrow(expand_calendar(calendars$m12,
  year = 2020, by = "day"))
[1] 366
base_calendar(years, by, tz) py
The real instant grid every conversion routes through (8784 hours in 2020).
drop_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.

Hourly data to timeslices
w <- merra2_cities[
  merra2_cities$city == "Reykjavik", ]
w$timeslice <- dtm2tsl(w$datetime, cal)
w <- aggregate(W50M ~ timeslice, w, mean)
Icicle of m12_h24 filled with Reykjavik wind speed at 50 m in 2019, from the annual mean to month by hour

gg_calendar(cal, data = w, z = "W50M", year = 2019): each band holds the value recast to its timeframe.

Recast between calendars
recast_calendar(data, source, target, year, values, rule, by, na_action, parent, …) py
Values from one calendar to another through the datetime grid of year. 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
Q1 = (31·120 + 28·118 + 31·105) / 90.
recast_calendar(m, calendars$m12,
  "ANNUAL", year = 2025, rule = "sum")
  timeslice load
1    ANNUAL 1218
A timeframe name of 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".

Attach a calendar to data
join_calendar(data, calendar, key, timeframes, meta, tokens, …) py
Adds a column named after the calendar, plus <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, else datetime.
  • 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.
Route, crosswalks, registries
recast_to_datetime(data, calendar, year, rule, by, attach_weight, …) py
recast_from_datetime(data, calendar, year, rule, by, na_action, …) py
The two halves of recast_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, …) py
The crosswalk a recast joins: overlapping pairs, grid counts n_from, n_overlap, weight w. calendar_map(): two timeframes of one calendar.
register_calendar_rule(param, rule) py
A rule per value-column name.
register_calendar_map_between(source, target, map, …) py
A known crosswalk replaces the grid derivation.
register_calendar_conversion(source, target, fun, …) py
A function replaces the whole conversion for a named pair.

get_*, 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.

Python
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; py marks 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) is ts.calendar_summary(x), print(x) is str(x); clear_* also take name. Figures stay in R.
Data on a calendar
Helsinki wind speed at 50 m in 2019, by day of year and hour
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, …)
One tile layer from a datetime or a timeslice column. Inputs are column names, not aes(); by = carries facet columns.
Assembled figures
Wall calendar of Helsinki daily mean temperature in 2019
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, …)
type = "icicle" (default, also autoplot()), "stack", "heatmap", "wall".

calendar_layout(), calendar_wall_layout(), calendar_weekdays(): the plain data frames behind the figures. calendar_breaks() thins a dense axis.