Skip to main content

Note 28: Temporal Data Wrangling: Irregular Timestamps, Sentinels & Gaps

Module 7: Wrangling, Case Studies & Ethics

Learning Objectives

  • Parse heterogeneous date-time strings into standardized POSIXct indices using lubridate::parse_date_time() with complete format vectors, explicit time zones, and component builders (make_date()).
  • Detect and repair real-world ingestion hazards: non-US delimiters, European comma decimal marks, sentinel missing-value codes (such as -200), and daylight saving time (DST) collisions.
  • Construct regular tsibble grids, audit implicit and explicit outages via scan_gaps() and count_gaps(), and aggregate cleanly with index_by().
  • Compare linear interpolation against state-space Kalman smoothing for multi-day sensor gaps and evaluate how each alters series variance.

1. Parsing Heterogeneous Timestamps & Time-Zone Pitfalls

Operational logs and scraped telemetry rarely obey ISO 8601 (YYYY-MM-DD HH:MM:SS). A single column may mix 24-hour stamps, spelled-out months, European d/m/Y dates, and 12-hour am/pm clocks. Calling a single-format parser such as ymd_hms() silently turns unmatched rows into NA.

Instead, lubridate::parse_date_time() accepts an ordered vector of candidate templates (orders), including "B d, Y HM" for spelled-out months and "B d Y Ip" for 12-hour clocks with am/pm indicators. Always pass an explicit tz argument so timestamps do not inherit the analyst’s local machine clock.

log_raw <- tibble(
  event_id = 1:6,
  raw_time = c(
    "2024-03-05 14:32:11",
    "07/03/2024 12:00",
    "March 10, 2024 17:20",
    "April 5th 2023, 10pm",
    "2024-03-08T15:05:01",
    "20240313 081500"
  )
)

log_parsed <- log_raw |>
  mutate(
    timestamp_utc = parse_date_time(
      raw_time,
      orders = c("Ymd HMS", "B d, Y HM", "d/m/Y H:M", "B d Y Ip"),
      tz = "UTC"
    )
  )

log_parsed |> fmt_tbl(caption = "Heterogeneous timestamps parsed cleanly into UTC.")
Heterogeneous timestamps parsed cleanly into UTC.
event_id raw_time timestamp_utc
1 2024-03-05 14:32:11 2024-03-05 14:32:11
2 07/03/2024 12:00 2024-03-07 12:00:00
3 March 10, 2024 17:20 2024-03-10 17:20:00
4 April 5th 2023, 10pm 2023-04-05 22:00:00
5 2024-03-08T15:05:01 2024-03-08 15:05:01
6 20240313 081500 2024-03-13 08:15:00

When dates arrive split across integer or text columns, construct them deterministically with make_date() or make_datetime() rather than string concatenation.

sensor_parts <- tibble(
  station = c("North", "Central", "South"),
  yr = c(2024, 2024, 2024),
  mth = c("February", "March", "April"),
  dy = c(29, 15, 1)
) |>
  mutate(date = make_date(yr, match(mth, month.name), dy))

sensor_parts |> fmt_tbl(caption = "Reconstructing Date indices from separate calendar components.")
Reconstructing Date indices from separate calendar components.
station yr mth dy date
North 2024 February 29 2024-02-29
Central 2024 March 15 2024-03-15
South 2024 April 1 2024-04-01

Time zones also introduce subtle duplicate-index bugs during daylight saving transitions. On a spring-forward night, the skipped wall-clock hour (for example, 02:00 in Europe/Rome) does not exist locally; on a fall-back night, the repeated hour occurs twice. Hardware loggers typically record in fixed standard time or UTC, so forcing a DST-observing local zone onto fixed-clock telemetry collapses or duplicates timestamps and breaks as_tsibble().

2. Ingestion Hazards: Delimiters, Decimal Marks & Sentinel Codes

The UCI Italian Air Quality dataset (data/AirQualityUCI.csv) combines four classic ingestion traps in one file:

  1. Semicolon (;) field delimiters instead of commas.
  2. European decimal commas (2,6, 13,6, 0,7578) that default numeric parsers misread.
  3. Missing sensor readings encoded as the sentinel value -200 (and -200,0).
  4. Two trailing empty columns (;;) and 114 blank trailing rows at the end of the file.

Applying readr::parse_number() under default US locale silently strips the comma from "2,6" and produces 26 (a tenfold inflation!). Likewise, computing a mean before recoding -200 to NA yields a physically impossible negative CO concentration.

aq_naive <- read_delim(
  "data/AirQualityUCI.csv", delim = ";",
  name_repair = "unique_quiet", show_col_types = FALSE
) |>
  clean_names() |>
  filter(!is.na(date))

aq_clean <- read_delim(
  "data/AirQualityUCI.csv",
  delim = ";",
  locale = locale(decimal_mark = ","),
  na = c("", "NA", "-200", "-200,0"),
  name_repair = "unique_quiet",
  show_col_types = FALSE
) |>
  clean_names() |>
  select(-starts_with("x")) |>
  filter(!is.na(date), !is.na(time))

tibble(
  Pipeline = c("Default parse_number() on '2,6'", "Locale decimal_mark = ',' (with -200 intact)", "Proper locale + sentinel NA recoding"),
  `First CO(GT)` = c(parse_number(aq_naive$co_gt[1]), as.numeric(gsub(",", ".", aq_naive$co_gt[1])), aq_clean$co_gt[1]),
  `Sample Mean CO(GT)` = c(
    mean(parse_number(aq_naive$co_gt), na.rm = TRUE),
    mean(as.numeric(gsub(",", ".", aq_naive$co_gt)), na.rm = TRUE),
    mean(aq_clean$co_gt, na.rm = TRUE)
  )
) |> fmt_tbl(digits = 2, caption = "Impact of locale decimal marks and -200 sentinel codes on CO(GT) (mg/m^3).")
Impact of locale decimal marks and -200 sentinel codes on CO(GT) (mg/m^3).
Pipeline First CO(GT) Sample Mean CO(GT)
Default parse_number() on ‘2,6’ 26.0 -37.00
Locale decimal_mark = ‘,’ (with -200 intact) 2.6 -34.21
Proper locale + sentinel NA recoding 2.6 2.15

Leaving -200 uncleaned drags the sample CO mean from 2.15 mg/m³ down to -34.21 mg/m³. Always inspect raw headers, tails, and minimum values before summarizing any external CSV.

3. Regular Hourly Grids, DST Audits & Daily Aggregation

Because the Italian monitoring station logged on a fixed standard-time clock (no spring-forward skip), parsing timestamps in "Europe/Rome" forces 2004-03-28 02:00 and 2005-03-27 02:00 onto 03:00, creating two duplicate keys. Parsing in fixed UTC (dmy(date) + hms(time)) preserves a strictly unique, regular 1-hour grid across all 9,357 hours (2004-03-10 18:00 to 2005-04-04 14:00).

aq_rome_dups <- aq_clean |>
  mutate(
    dt_rome = make_datetime(
      year(dmy(date)), month(dmy(date)), day(dmy(date)),
      hour = as.integer(substr(time, 1, 2)), tz = "Europe/Rome"
    )
  ) |>
  summarise(n_duplicates = sum(duplicated(dt_rome)))

aq_hourly <- aq_clean |>
  mutate(datetime = dmy(date) + hms(time)) |>
  as_tsibble(index = datetime)

tibble(
  `Europe/Rome DST duplicates` = aq_rome_dups$n_duplicates,
  `UTC hourly rows` = nrow(aq_hourly),
  `Implicit hourly gaps` = nrow(scan_gaps(aq_hourly)),
  `Missing CO(GT) hours` = sum(is.na(aq_hourly$co_gt)),
  `Missing Temp hours` = sum(is.na(aq_hourly$t))
) |> fmt_tbl(caption = "Timestamp integrity and missing-hour audit for AirQualityUCI.csv.")
Timestamp integrity and missing-hour audit for AirQualityUCI.csv.
Europe/Rome DST duplicates UTC hourly rows Implicit hourly gaps Missing CO(GT) hours Missing Temp hours
2 9357 0 1683 366

Notice the distinction between implicit gaps (missing rows in the index, audited by scan_gaps()) and explicit missing values (NA entries inside existing rows). Here the hourly index has zero implicit gaps, yet co_gt is NA in 1,683 hours (18.0%) due to sensor recalibration outages.

To study day-to-day air quality, aggregate via index_by() and summarise(). When all 24 hours on a day are NA, mean(..., na.rm = TRUE) returns NaN, which we convert back to NA_real_ before calling fill_gaps().

aq_daily <- aq_hourly |>
  index_by(day = ~ as_date(.)) |>
  summarise(
    co = mean(co_gt, na.rm = TRUE),
    temp = mean(t, na.rm = TRUE),
    no2 = mean(no2_gt, na.rm = TRUE)
  ) |>
  mutate(across(c(co, temp, no2), ~ ifelse(is.nan(.), NA_real_, .))) |>
  fill_gaps()

aq_daily |>
  filter(!is.na(co)) |>
  count_gaps() |>
  arrange(desc(.n)) |>
  head(5) |>
  fmt_tbl(caption = "Five longest contiguous daily CO(GT) sensor outages.")
Five longest contiguous daily CO(GT) sensor outages.
.from .to .n
2004-10-14 2004-10-19 6
2004-04-18 2004-04-22 5
2004-10-02 2004-10-06 5
2004-07-27 2004-07-30 4
2004-08-20 2004-08-22 3

4. Comparing Gap Imputation Methods

Many downstream tools (such as STL decomposition or spectral estimation) require a complete regular grid without NA values. Let \(y_t\) be an observed series with an outage spanning \(t \in \{t_1+1, \dots, t_2-1\}\). Two common approaches behave very differently across multi-day outages:

  • Linear interpolation connects endpoints directly: \[\hat{y}_t = y_{t_1} + \frac{t - t_1}{t_2 - t_1}(y_{t_2} - y_{t_1}), \quad t_1 < t < t_2.\] It is fast and transparent, but a single extreme reading at \(t_1\) or \(t_2\) pulls the entire bridge toward that boundary outlier.
  • Kalman smoothing (imputeTS::na_kalman(model = "StructTS")) fits a local-level/trend state-space model by maximum likelihood and computes the conditional expectation \(\hat{y}_t = \mathbb{E}[y_t \mid y_{1:T}]\) given all observed data, shrinking extreme boundary jumps back toward the local state level.
aq_imp <- aq_daily |>
  mutate(
    Linear = na_interpolation(co, option = "linear"),
    Kalman = na_kalman(co, model = "StructTS")
  )

aq_imp |>
  filter(day >= as_date("2004-09-20"), day <= as_date("2004-11-05")) |>
  pivot_longer(c(Linear, Kalman), names_to = "Method", values_to = "Imputed") |>
  ggplot(aes(x = day)) +
  geom_line(aes(y = Imputed, color = Method, linetype = Method), linewidth = 0.85) +
  geom_point(aes(y = co), color = ts_pal["navy"], size = 1.6, na.rm = TRUE) +
  scale_color_manual(values = c(Linear = unname(ts_pal["orange"]), Kalman = unname(ts_pal["teal"]))) +
  scale_linetype_manual(values = c(Linear = "dashed", Kalman = "solid")) +
  labs(
    title = "Daily CO(GT) Outage Imputation: Linear vs. Kalman Smoothing",
    subtitle = "Dots mark observed daily means; October 14–19 shows a 6-day sensor outage",
    x = "Date (2004)",
    y = bquote(bold("Mean CO concentration (mg/" * "m"^3 * ")")),
    color = "Imputation",
    linetype = "Imputation"
  )
Figure 1: Comparison of linear interpolation and Kalman state-space smoothing across daily CO(GT) sensor outages, highlighting the 6-day October 2004 outage.

Across the six-day October 14–19 outage (Figure 1), the first day back online (2004-10-20) happens to be a pollution spike (5.65 mg/m³). Linear interpolation climbs rigidly from 1.35 to 5.65, inflating imputed values near the right boundary, whereas Kalman smoothing stays near the autumn baseline (2.48 to 3.11). Whenever gaps exceed one or two steps, always plot the imputed bridge alongside observed points and report what fraction of observations were imputed.

Practice Exercises

  1. Parsing Mixed 12-Hour and 24-Hour Logs. Parse the following messy_logins table cleanly into UTC POSIXct timestamps with zero NA failures, verifying that "April 5th 2023, 10pm" parses to 22:00:00:

    messy_logins <- tibble(
      event_time = c(
        "2023-04-05 22:00", "2023/04/06 08:30",
        "April 5th 2023, 10pm", "2023-04-07", "15-04-2023 12:00"
      )
    )
Solution

Specify "B d Y Ip" so lubridate reads the 12-hour pm meridian properly (I = 12-hour clock, p = am/pm), alongside "Ymd HM", "dmy HM", and "Ymd":

messy_logins <- tibble(
  event_time = c(
    "2023-04-05 22:00", "2023/04/06 08:30",
    "April 5th 2023, 10pm", "2023-04-07", "15-04-2023 12:00"
  )
)

messy_logins |>
  mutate(
    clean_utc = parse_date_time(
      event_time,
      orders = c("Ymd HM", "B d Y Ip", "dmy HM", "Ymd"),
      tz = "UTC"
    )
  ) |>
  fmt_tbl(caption = "Verified UTC timestamps for all five mixed-format entries.")
Verified UTC timestamps for all five mixed-format entries.
event_time clean_utc
2023-04-05 22:00 2023-04-05 22:00:00
2023/04/06 08:30 2023-04-06 08:30:00
April 5th 2023, 10pm 2023-04-05 22:00:00
2023-04-07 2023-04-07 00:00:00
15-04-2023 12:00 2023-04-15 12:00:00
  1. Auditing Gap Structure Across Sensors. Using aq_daily from data/AirQualityUCI.csv, compare the total number of missing days, number of distinct outage spells, and maximum outage duration between daily co and daily temp.
Solution

Filter non-missing rows for each sensor and apply count_gaps() to enumerate contiguous missing spells:

gap_summary <- function(tbl, col) {
  gaps <- tbl |> filter(!is.na({{ col }})) |> count_gaps()
  tibble(
    Missing_Days = sum(is.na(pull(tbl, {{ col }}))),
    Outage_Spells = nrow(gaps),
    Max_Spell_Days = max(gaps$.n)
  )
}

bind_rows(
  gap_summary(aq_daily, co) |> mutate(Sensor = "CO (mg/m^3)", .before = 1),
  gap_summary(aq_daily, temp) |> mutate(Sensor = "Temperature (C)", .before = 1)
) |> fmt_tbl(caption = "Daily outage comparison between CO and temperature sensors.")
Daily outage comparison between CO and temperature sensors.
Sensor Missing_Days Outage_Spells Max_Spell_Days
CO (mg/m^3) 36 14 6
Temperature (C) 8 5 2

The chemical CO analyzer suffered 36 missing days (up to 6 consecutive days), whereas the simpler temperature probe missed only 8 days (maximum 2 consecutive days).

Key Takeaways

  • Always parse heterogeneous timestamp columns with parse_date_time(), explicit format vectors (including "Ip" for 12-hour clocks), and an explicit tz = "UTC" unless local DST semantics are verified.
  • Check raw delimiters, locale decimal marks (decimal_mark = ","), trailing blank rows/columns, and sentinel values like -200 at import time; silent parsing errors can alter series levels by an order of magnitude.
  • Distinguish implicit index gaps (scan_gaps(), count_gaps()) from explicit NA entries, and convert NaN values created by all-NA daily aggregations back to NA_real_.
  • Linear interpolation bridges endpoints mechanically and overreacts to boundary spikes, while Kalman smoothing incorporates global dynamics; always visualize and disclose imputed spans.
Back to top