Dates, Times, and Temporal Order
A questionnaire schedule and its submitted responses may use different time zones. Measuring the gap between them requires interpreting both clock readings consistently. Even then, comparing scores requires a further choice: if a participant skips a day, the previous recorded score is no longer yesterday’s score. This chapter develops the information needed for both decisions. We first interpret date and time text and distinguish elapsed durations from positions in the calendar. We then resolve time-zone differences and order observations, making explicit which earlier value each comparison uses.
11.1 Parsing dates and date times
03/04/2024 means April 3 under a day-first convention and March 4 under a month-first convention. Both are valid dates, so a parser can accept the wrong interpretation without an error. The source format must specify the order of day, month and year.
The momentary-assessment study schedules five short questionnaire prompts per participant each day. Each row of ema_schedule.csv gives the scheduled time of one prompt, identified by participant id, study day and prompt number within the day. E001’s first prompt_time is 2024-04-01 09:47:00. The year, month and day come first, followed by the scheduled hour, minute and second.
Reading these fields establishes the calendar date and clock time. Locating that reading in time also requires its source zone. A time zone relates a local clock to Coordinated Universal Time (UTC), the common time reference, on a given date.
The names of the lubridate parsers give the order of the fields. dmy() reads the day first and mdy() reads the month first. For E001’s first prompt on day 1, str_sub(prompt_time, 1, 10) extracts the date text and ymd() reads the year first, followed by the month and day.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
library(tidyverse)
dmy("03/04/2024")
mdy("03/04/2024")
schedule <- read_csv(
"data/practice/ema_schedule.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
schedule_dates <- schedule |>
filter(id == "E001", day == "1", prompt == "1") |>
select(id, day, prompt, prompt_time) |>
mutate(date_text = str_sub(prompt_time, 1, 10), date = ymd(date_text))
select(schedule_dates, id, date_text, date)
class(schedule_dates$date)
1
2
3
4
5
6
7
[1] "2024-04-03"
[1] "2024-03-04"
# A tibble: 1 × 3
id date_text date
<chr> <chr> <date>
1 E001 2024-04-01 2024-04-01
[1] "Date"
The same string gives April 3 with dmy() and March 4 with mdy(). For E001, both columns display 2024-04-01. date_text contains ten characters. date has class Date, so subtracting another date from it gives a difference in days.
The first row of sub-001_ses-1.csv, an older trial export, records stimulus onset as 26/03/2024 09:54:27. The Time field starts with the day. lubridate::dmy_hms() reads day, month, year, hours, minutes and seconds, while mdy_hms() expects the month first. The trial clock used Asia/Seoul. With the zone omitted from dmy_hms(), tz() shows which zone the parser assumes.
1
2
3
4
5
6
7
8
9
10
11
12
13
trial_old <- read_csv(
"data/raw/trials/sub-001_ses-1.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
onset_old <- trial_old |>
select(Participant, Block, Trial, Time) |>
head(1) |>
mutate(onset = dmy_hms(Time))
onset_old
tz(onset_old$onset)
mdy_hms(onset_old$Time)
1
2
3
4
5
6
7
8
# A tibble: 1 × 5
Participant Block Trial Time onset
<chr> <chr> <chr> <chr> <dttm>
1 sub-001 0 1 26/03/2024 09:54:27 2024-03-26 09:54:27
[1] "UTC"
[1] NA
Warning message:
All formats failed to parse. No formats found.
The day-first parse gives March 26 at 09:54:27. tz() reports UTC because dmy_hms() used its default. Reading 09:54:27 as UTC places this trial nine hours later than its recorded Seoul time. The month-first parse fails because 26 cannot be a month.
Polars str.to_date() uses %d for day, %m for month and %Y for four-digit year, with separators as written. Swapping %d and %m changes the interpretation of the ambiguous date. For E001’s first prompt, the schedule text uses year first. str.slice(0, 10) takes its ten date characters starting at position zero, and %Y-%m-%d gives their order to the parser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import polars as pl
ambiguous = pl.Series("recorded", ["03/04/2024"])
ambiguous.str.to_date("%d/%m/%Y").to_list()
ambiguous.str.to_date("%m/%d/%Y").to_list()
schedule = pl.read_csv("data/practice/ema_schedule.csv", infer_schema=False)
schedule_dates = (
schedule.filter(
(pl.col("id") == "E001") & (pl.col("day") == "1") & (pl.col("prompt") == "1")
)
.select("id", "day", "prompt", "prompt_time")
.with_columns(date_text=pl.col("prompt_time").str.slice(0, 10))
.with_columns(date=pl.col("date_text").str.to_date("%Y-%m-%d"))
)
schedule_dates.select("id", "date_text", "date")
1
2
3
4
5
6
7
8
9
10
[datetime.date(2024, 4, 3)]
[datetime.date(2024, 3, 4)]
shape: (1, 3)
┌──────┬────────────┬────────────┐
│ id ┆ date_text ┆ date │
│ --- ┆ --- ┆ --- │
│ str ┆ str ┆ date │
╞══════╪════════════╪════════════╡
│ E001 ┆ 2024-04-01 ┆ 2024-04-01 │
└──────┴────────────┴────────────┘
For E001, both columns display 2024-04-01. The str column contains the original date characters. The parsed dates can be subtracted to find how many days apart they are.
In the older trial export, Time records stimulus onset. Its first date, 26/03/2024, starts with the day. In Polars, str.to_datetime("%d/%m/%Y %H:%M:%S") reads that date followed by hours, minutes and seconds. The dtype shows the time unit and whether the parsed value has a zone.
1
2
3
4
5
6
7
8
trial_old = pl.read_csv("data/raw/trials/sub-001_ses-1.csv", infer_schema=False)
onset_old = (
trial_old.select("Participant", "Block", "Trial", "Time")
.head(1)
.with_columns(onset=pl.col("Time").str.to_datetime("%d/%m/%Y %H:%M:%S"))
)
onset_old
onset_old.schema["onset"]
1
2
3
4
5
6
7
8
9
shape: (1, 5)
┌─────────────┬───────┬───────┬─────────────────────┬─────────────────────┐
│ Participant ┆ Block ┆ Trial ┆ Time ┆ onset │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ datetime[μs] │
╞═════════════╪═══════╪═══════╪═════════════════════╪═════════════════════╡
│ sub-001 ┆ 0 ┆ 1 ┆ 26/03/2024 09:54:27 ┆ 2024-03-26 09:54:27 │
└─────────────┴───────┴───────┴─────────────────────┴─────────────────────┘
Datetime(time_unit='us', time_zone=None)
The trial clock read 09:54:27 in Seoul. time_zone=None means Polars has read the clock fields without assigning a zone, so finding the UTC time also requires the source zone. time_unit='us' means the column can store fractions of a second down to microseconds.
The newer trial export for sub-006 records stimulus onset as 2024-03-15 12:24:21.500. Did the parser read the half second even if the table prints only whole seconds? In lubridate, second() extracts the seconds within the minute after ymd_hms() parses the timestamp. In Polars, %.f reads the fractional seconds and dt.millisecond() returns the millisecond component.
1
2
3
4
5
6
7
8
9
10
11
12
trial_new <- read_csv(
"data/raw/trials/sub-006_ses-1.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
onset_new <- trial_new |>
select(participant, block, trial, timestamp) |>
head(1) |>
mutate(onset = ymd_hms(timestamp))
onset_new
c(second(onset_old$onset), second(onset_new$onset))
1
2
3
4
5
# A tibble: 1 × 5
participant block trial timestamp onset
<chr> <chr> <chr> <chr> <dttm>
1 sub-006 0 1 2024-03-15 12:24:21.500 2024-03-15 12:24:21
[1] 27.0 21.5
1
2
3
4
5
6
7
8
9
trial_new = pl.read_csv("data/raw/trials/sub-006_ses-1.csv", infer_schema=False)
onset_new = (
trial_new.select("participant", "block", "trial", "timestamp")
.head(1)
.with_columns(onset=pl.col("timestamp").str.to_datetime("%Y-%m-%d %H:%M:%S%.f"))
)
onset_new
onset_new.schema["onset"] == onset_old.schema["onset"]
(onset_old["onset"].dt.millisecond()[0], onset_new["onset"].dt.millisecond()[0])
1
2
3
4
5
6
7
8
9
10
shape: (1, 5)
┌─────────────┬───────┬───────┬─────────────────────────┬─────────────────────────┐
│ participant ┆ block ┆ trial ┆ timestamp ┆ onset │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ str ┆ datetime[μs] │
╞═════════════╪═══════╪═══════╪═════════════════════════╪═════════════════════════╡
│ sub-006 ┆ 0 ┆ 1 ┆ 2024-03-15 12:24:21.500 ┆ 2024-03-15 12:24:21.500 │
└─────────────┴───────┴───────┴─────────────────────────┴─────────────────────────┘
True
(0, 500)
The tibble displays 12:24:21, but second() returns 21.5 seconds into the minute. Polars gives both columns the same microsecond type. It reports 500 milliseconds for the newer reading and 0 for the older one. The older source records only whole seconds, so we cannot tell whether the stimulus appeared exactly on the second.
Formatting produces text from a parsed value. In R’s format(), %OS3 requests seconds with three decimal places. In Polars, dt.strftime() uses %.3f for the fraction. The old reading provides a test case because its source records only whole seconds.
1
2
3
4
old_display <- format(onset_old$onset, "%Y-%m-%d %H:%M:%OS3")
old_display
class(old_display)
onset_old$onset
1
2
3
[1] "2024-03-26 09:54:27.000"
[1] "character"
[1] "2024-03-26 09:54:27 UTC"
1
onset_old.select("onset", display=pl.col("onset").dt.strftime("%Y-%m-%d %H:%M:%S%.3f"))
1
2
3
4
5
6
7
8
shape: (1, 2)
┌─────────────────────┬─────────────────────────┐
│ onset ┆ display │
│ --- ┆ --- │
│ datetime[μs] ┆ str │
╞═════════════════════╪═════════════════════════╡
│ 2024-03-26 09:54:27 ┆ 2024-03-26 09:54:27.000 │
└─────────────────────┴─────────────────────────┘
The .000 in both displays comes from the format. The old file gives no fraction of a second. The original R value still uses UTC by default, and the original Polars value still has no assigned zone.
11.2 Durations, intervals, and calendar components
How many seconds separate E001’s first two scheduled prompts on day 1, 2024-04-01 09:47:00 and 2024-04-01 12:58:00? Both times use the Seoul clock, Asia/Seoul, so subtracting the first scheduled time from the second gives the gap.
With E001’s two prompts in order, ymd_hms(..., tz = "Asia/Seoul") interprets each clock reading in Seoul time. Subtracting start from end returns a duration, an amount of elapsed time, stored as a difftime with a unit. difftime(..., units = "secs") requests seconds, and as.numeric() gives that count as a number.
1
2
3
4
5
6
7
8
9
first_pair <- schedule |>
filter(id == "E001", day == "1", prompt %in% c("1", "2")) |>
arrange(prompt) |>
mutate(time = ymd_hms(prompt_time, tz = "Asia/Seoul"))
select(first_pair, id, prompt, prompt_time)
first_interval <- tibble(start = first_pair$time[1], end = first_pair$time[2]) |>
mutate(elapsed = as.numeric(difftime(end, start, units = "secs")))
first_interval$end - first_interval$start
first_interval$elapsed
1
2
3
4
5
6
7
# A tibble: 2 × 3
id prompt prompt_time
<chr> <chr> <chr>
1 E001 1 2024-04-01 09:47:00
2 E001 2 2024-04-01 12:58:00
Time difference of 3.183333 hours
[1] 11460
For this pair, R displays 3.183333 hours, or 3 hours and 11 minutes. In seconds, the gap between the two scheduled prompts is 11,460. The schedule gives no measure of how long E001 spent answering.
In Polars, str.to_datetime() interprets both prompt times in Seoul with time_zone="Asia/Seoul". Once the two prompts are in order, head(1) and tail(1) give the start and end Series with their datetime type. Subtracting start from end gives a duration, the elapsed time between them. dt.total_seconds() expresses it in seconds.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
first_pair = (
schedule.filter(
(pl.col("id") == "E001")
& (pl.col("day") == "1")
& pl.col("prompt").is_in(["1", "2"])
)
.sort("prompt")
.with_columns(
time=pl.col("prompt_time").str.to_datetime(
"%Y-%m-%d %H:%M:%S", time_zone="Asia/Seoul"
)
)
)
first_pair.select("id", "prompt", "prompt_time").rows()
first_interval = pl.DataFrame({"start": first_pair["time"].head(1),
"end": first_pair["time"].tail(1)})
first_interval = first_interval.with_columns(interval=pl.col("end") - pl.col("start"))
first_interval = first_interval.with_columns(elapsed=pl.col("interval").dt.total_seconds())
first_interval.select("interval", "elapsed").rows()
1
2
[('E001', '1', '2024-04-01 09:47:00'), ('E001', '2', '2024-04-01 12:58:00')]
[(datetime.timedelta(seconds=11460), 11460)]
The first value, datetime.timedelta(seconds=11460), is a duration. The second gives the same gap in seconds. The prompts were scheduled 3 hours and 11 minutes apart. Measuring time spent answering would require the start and end of a response.
Elapsed time and calendar positions
In a constructed overnight interval, the start is 23:30 on April 1 and the end is 00:30 on April 2. The clock hour drops from 23 to 0 while the date advances. In R, hour() extracts the clock hour and difftime() measures the interval in hours. In Polars, dt.hour() extracts the clock hour and dt.total_hours() gives the duration in hours.
1
2
3
4
overnight_start <- ymd_hm("2024-04-01 23:30", tz = "Asia/Seoul")
overnight_end <- ymd_hm("2024-04-02 00:30", tz = "Asia/Seoul")
hour(overnight_end) - hour(overnight_start)
difftime(overnight_end, overnight_start, units = "hours")
1
2
[1] -23
Time difference of 1 hours
1
2
3
4
5
6
7
8
overnight = pl.DataFrame({"start": ["2024-04-01 23:30"], "end": ["2024-04-02 00:30"]})
overnight = overnight.select(
pl.col("start", "end").str.to_datetime("%Y-%m-%d %H:%M", time_zone="Asia/Seoul")
)
overnight.select(
hour_difference=pl.col("end").dt.hour() - pl.col("start").dt.hour(),
elapsed_hours=(pl.col("end") - pl.col("start")).dt.total_hours(),
)
1
2
3
4
5
6
7
8
shape: (1, 2)
┌─────────────────┬───────────────┐
│ hour_difference ┆ elapsed_hours │
│ --- ┆ --- │
│ i8 ┆ i64 │
╞═════════════════╪═══════════════╡
│ -23 ┆ 1 │
└─────────────────┴───────────────┘
The hour components differ by -23, but the full interval is one hour. Including the date accounts for crossing midnight.
The first prompt’s year, month and day locate it on the calendar. What does subtracting the month numbers tell us about the time from March 31 to April 1?
1
2
3
c(year(first_interval$start), month(first_interval$start), day(first_interval$start))
month(ymd("2024-04-01")) - month(ymd("2024-03-31"))
ymd("2024-04-01") - ymd("2024-03-31")
1
2
3
[1] 2024 4 1
[1] 1
Time difference of 1 days
1
2
3
4
5
6
7
8
9
10
11
first_interval.select(
year=pl.col("start").dt.year(),
month=pl.col("start").dt.month(),
day=pl.col("start").dt.day(),
)
boundary = pl.DataFrame({"earlier": ["2024-03-31"], "later": ["2024-04-01"]})
boundary = boundary.select(pl.col("earlier", "later").str.to_date("%Y-%m-%d"))
boundary.select(
month_difference=pl.col("later").dt.month() - pl.col("earlier").dt.month(),
elapsed_days=(pl.col("later") - pl.col("earlier")).dt.total_days(),
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
shape: (1, 3)
┌──────┬───────┬─────┐
│ year ┆ month ┆ day │
│ --- ┆ --- ┆ --- │
│ i32 ┆ i8 ┆ i8 │
╞══════╪═══════╪═════╡
│ 2024 ┆ 4 ┆ 1 │
└──────┴───────┴─────┘
shape: (1, 2)
┌──────────────────┬──────────────┐
│ month_difference ┆ elapsed_days │
│ --- ┆ --- │
│ i8 ┆ i64 │
╞══════════════════╪══════════════╡
│ 1 ┆ 1 │
└──────────────────┴──────────────┘
The first prompt falls on April 1, 2024. From March 31 to April 1, the month number advances from 3 to 4. Subtracting the dates also gives 1, but here it means that only one day passed across the month boundary. From March 1 to April 1 the month number also advances by one, although 31 days pass.
Minutes since midnight
To compare the time of day at which prompts are scheduled, we can express each clock reading as minutes since midnight. At 09:47, nine hours have passed since midnight, or 540 minutes. Another 47 minutes brings the total to 587, the first prompt’s clock position within that day.
For the first prompt, hour(reading) * 60L + minute(reading) does the calculation with integers. typeof() gives the type of the result.
1
2
3
4
5
reading <- first_interval$start
c(hour(reading), minute(reading))
minutes_since_midnight <- hour(reading) * 60L + minute(reading)
minutes_since_midnight
typeof(minutes_since_midnight)
1
2
3
[1] 9 47
[1] 587
[1] "integer"
R returns integer 587. Both the intermediate 540 and the final sum fit its ordinary integer range.
The Polars methods dt.hour() and dt.minute() return Int8 here. Nine hours fit in that type, but 540 minutes do not. The widened expression casts the hour to Int16 before multiplying by 60 and adding the minute component.
1
2
3
4
5
6
7
reading = first_interval.select(clock=pl.col("start"))
reading.select(
hour=pl.col("clock").dt.hour(),
minute=pl.col("clock").dt.minute(),
narrow=pl.col("clock").dt.hour() * 60 + pl.col("clock").dt.minute(),
widened=pl.col("clock").dt.hour().cast(pl.Int16) * 60 + pl.col("clock").dt.minute(),
)
1
2
3
4
5
6
7
8
shape: (1, 4)
┌──────┬────────┬────────┬─────────┐
│ hour ┆ minute ┆ narrow ┆ widened │
│ --- ┆ --- ┆ --- ┆ --- │
│ i8 ┆ i8 ┆ i8 ┆ i16 │
╞══════╪════════╪════════╪═════════╡
│ 9 ┆ 47 ┆ 75 ┆ 587 │
└──────┴────────┴────────┴─────────┘
The narrow result is 75 without a warning because the intermediate 540 wraps to 28 in Int8 before 47 is added. Widening first gives the required 587. Casting afterward would only widen the already incorrect result.
In both implementations, 587 identifies 09:47 within the local day. It describes a clock position, not the elapsed time between two observations. Comparing records also requires their dates and the time zones of their source clocks.
11.3 Local clock readings, time zones, and instants
Two constructed readings for April 1, 2024, show 09:30 in Seoul and 00:30 in UTC. Seoul was nine hours ahead of UTC that day, so both clocks showed the same instant, a single point in time.
The text 2024-04-01 09:30 alone names no zone. Assigning Asia/Seoul identifies the instant the Seoul clock recorded. Converting that instant to UTC tells us what a UTC clock showed then.
The tz argument of lubridate::ymd_hm() specifies which clock each string came from. R stores the parsed instant as seconds since the start of 1970 in UTC and uses the time zone to display the local date and time.
1
2
3
4
5
6
7
seoul_text <- "2024-04-01 09:30"
utc_text <- "2024-04-01 00:30"
seoul_reading <- ymd_hm(seoul_text, tz = "Asia/Seoul")
utc_reading <- ymd_hm(utc_text, tz = "UTC")
c(seoul_text, utc_text)
seoul_reading
utc_reading
1
2
3
[1] "2024-04-01 09:30" "2024-04-01 00:30"
[1] "2024-04-01 09:30:00 KST"
[1] "2024-04-01 00:30:00 UTC"
The first parsed value shows 09:30 in Korea Standard Time (KST). The second shows 00:30 UTC. Neither source string includes those labels.
with_tz() displays the Seoul instant on a UTC clock. force_tz() treats the original 09:30 as a UTC reading. Subtracting utc_reading from the converted value tests whether the two clocks recorded the same instant.
1
2
3
4
seoul_in_utc <- with_tz(seoul_reading, "UTC")
seoul_in_utc
difftime(seoul_in_utc, utc_reading, units = "secs")
force_tz(seoul_reading, "UTC")
1
2
3
[1] "2024-04-01 00:30:00 UTC"
Time difference of 0 secs
[1] "2024-04-01 09:30:00 UTC"
with_tz() gives 00:30 UTC, zero seconds from utc_reading. With force_tz(), the digits still read 09:30, which on a UTC clock is nine hours later.
In Polars, str.to_datetime() reads the two strings as local dates and times. Neither string names a zone, so dt.replace_time_zone() assigns the source zone to each reading.
1
2
3
4
5
6
7
8
9
10
11
clock_format = "%Y-%m-%d %H:%M"
pair = pl.DataFrame(
{"seoul_text": ["2024-04-01 09:30"], "utc_text": ["2024-04-01 00:30"]}
)
pair = pair.with_columns(
seoul=pl.col("seoul_text")
.str.to_datetime(clock_format)
.dt.replace_time_zone("Asia/Seoul"),
utc=pl.col("utc_text").str.to_datetime(clock_format).dt.replace_time_zone("UTC"),
)
pair
1
2
3
4
5
6
7
8
shape: (1, 4)
┌──────────────────┬──────────────────┬──────────────────────────┬─────────────────────────┐
│ seoul_text ┆ utc_text ┆ seoul ┆ utc │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ datetime[μs, Asia/Seoul] ┆ datetime[μs, UTC] │
╞══════════════════╪══════════════════╪══════════════════════════╪═════════════════════════╡
│ 2024-04-01 09:30 ┆ 2024-04-01 00:30 ┆ 2024-04-01 09:30:00 KST ┆ 2024-04-01 00:30:00 UTC │
└──────────────────┴──────────────────┴──────────────────────────┴─────────────────────────┘
The seoul column shows 09:30 in Korea Standard Time (KST), and utc shows 00:30 UTC. The column types identify the zones as Asia/Seoul and UTC.
Can Polars subtract these two readings while their columns have different time zones?
1
2
# Deliberate error: subtracting date-times in two different zones
pair.select(difference=pl.col("seoul") - pl.col("utc"))
1
polars.exceptions.SchemaError: failed to determine supertype of datetime[μs, Asia/Seoul] and datetime[μs, UTC]
Polars reports incompatible datetime zones. dt.convert_time_zone("UTC") expresses the Seoul reading in the same zone as the other column for subtraction. The conversion preserves the instant, represented here as microseconds from the start of 1970 UTC. dt.replace_time_zone("UTC") instead assigns UTC to the original clock digits.
1
2
3
4
5
pair.select(
seoul_in_utc=pl.col("seoul").dt.convert_time_zone("UTC"),
difference=pl.col("seoul").dt.convert_time_zone("UTC") - pl.col("utc"),
relabelled=pl.col("seoul").dt.replace_time_zone("UTC"),
)
1
2
3
4
5
6
7
8
shape: (1, 3)
┌─────────────────────────┬──────────────┬─────────────────────────┐
│ seoul_in_utc ┆ difference ┆ relabelled │
│ --- ┆ --- ┆ --- │
│ datetime[μs, UTC] ┆ duration[μs] ┆ datetime[μs, UTC] │
╞═════════════════════════╪══════════════╪═════════════════════════╡
│ 2024-04-01 00:30:00 UTC ┆ 0µs ┆ 2024-04-01 09:30:00 UTC │
└─────────────────────────┴──────────────┴─────────────────────────┘
seoul_in_utc shows 00:30 UTC. Its zero difference from utc confirms that both readings refer to the same instant. In relabelled, the digits still read 09:30, but on a UTC clock they refer to an instant nine hours later.
Source clock conventions
The schedule in ema_schedule.csv uses Seoul time. In ema_responses.csv, each row is a submitted questionnaire, with the participant in user_id and the submission time in submitted_at. According to the study’s recording conventions, submission times are in UTC except for E017’s, which are in Seoul time. Neither file includes a zone in its timestamp text. Reading every submission as UTC would place E017’s events nine hours too late.
The three examples are E017’s first scheduled prompt, an E009 submission and an E017 submission. zone records the convention for each row. ymd_hms() parses the digits, and force_tzs() then assigns each row’s source zone without changing its clock fields. tzone_out = "UTC" displays the resulting instants in a common zone.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
responses <- read_csv(
"data/practice/ema_responses.csv",
col_types = cols(.default = col_character()),
na = "",
trim_ws = FALSE
)
prompt_reading <- schedule |>
filter(id == "E017", day == "1", prompt == "1") |>
select(id, prompt_time) |>
mutate(
zone = "Asia/Seoul",
instant_utc = force_tzs(ymd_hms(prompt_time), tzones = zone, tzone_out = "UTC")
)
selected_events <- c("2024-04-01T00:31:32", "2024-04-08T10:13:32")
event_readings <- responses |>
filter(submitted_at %in% selected_events) |>
select(user_id, submitted_at) |>
mutate(
zone = if_else(user_id == "E017", "Asia/Seoul", "UTC"),
instant_utc = force_tzs(ymd_hms(submitted_at), tzones = zone, tzone_out = "UTC")
)
prompt_reading
event_readings
1
2
3
4
5
6
7
8
9
# A tibble: 1 × 4
id prompt_time zone instant_utc
<chr> <chr> <chr> <dttm>
1 E017 2024-04-08 10:04:00 Asia/Seoul 2024-04-08 01:04:00
# A tibble: 2 × 4
user_id submitted_at zone instant_utc
<chr> <chr> <chr> <dttm>
1 E009 2024-04-01T00:31:32 UTC 2024-04-01 00:31:32
2 E017 2024-04-08T10:13:32 Asia/Seoul 2024-04-08 01:13:32
E017’s 10:04 prompt becomes 01:04 UTC. E009’s submission was already recorded in UTC, so its clock reading requires no adjustment. E017’s 10:13:32 submission becomes 01:13:32 UTC.
In Polars, clock initially has no zone. For E017’s prompt and submission, dt.replace_time_zone() assigns Seoul time and dt.convert_time_zone() gives the UTC equivalent. E009’s submission already uses UTC, so assigning that zone is enough.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
responses = pl.read_csv("data/practice/ema_responses.csv", infer_schema=False)
prompt_reading = (
schedule.filter(
(pl.col("id") == "E017") & (pl.col("day") == "1") & (pl.col("prompt") == "1")
)
.select("id", "prompt_time")
.with_columns(
zone=pl.lit("Asia/Seoul"),
clock=pl.col("prompt_time").str.to_datetime("%Y-%m-%d %H:%M:%S"),
)
.with_columns(
instant_utc=pl.col("clock")
.dt.replace_time_zone("Asia/Seoul")
.dt.convert_time_zone("UTC")
)
)
selected_events = ["2024-04-01T00:31:32", "2024-04-08T10:13:32"]
event_readings = (
responses.filter(pl.col("submitted_at").is_in(selected_events))
.select("user_id", "submitted_at")
.with_columns(
zone=pl.when(pl.col("user_id") == "E017")
.then(pl.lit("Asia/Seoul"))
.otherwise(pl.lit("UTC")),
clock=pl.col("submitted_at").str.to_datetime("%Y-%m-%dT%H:%M:%S"),
)
.with_columns(
instant_utc=pl.when(pl.col("zone") == "Asia/Seoul")
.then(
pl.col("clock")
.dt.replace_time_zone("Asia/Seoul")
.dt.convert_time_zone("UTC")
)
.otherwise(pl.col("clock").dt.replace_time_zone("UTC"))
)
)
prompt_reading
event_readings
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
shape: (1, 5)
┌──────┬─────────────────────┬────────────┬─────────────────────┬─────────────────────────┐
│ id ┆ prompt_time ┆ zone ┆ clock ┆ instant_utc │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ datetime[μs] ┆ datetime[μs, UTC] │
╞══════╪═════════════════════╪════════════╪═════════════════════╪═════════════════════════╡
│ E017 ┆ 2024-04-08 10:04:00 ┆ Asia/Seoul ┆ 2024-04-08 10:04:00 ┆ 2024-04-08 01:04:00 UTC │
└──────┴─────────────────────┴────────────┴─────────────────────┴─────────────────────────┘
shape: (2, 5)
┌─────────┬─────────────────────┬────────────┬─────────────────────┬─────────────────────────┐
│ user_id ┆ submitted_at ┆ zone ┆ clock ┆ instant_utc │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ str ┆ datetime[μs] ┆ datetime[μs, UTC] │
╞═════════╪═════════════════════╪════════════╪═════════════════════╪═════════════════════════╡
│ E009 ┆ 2024-04-01T00:31:32 ┆ UTC ┆ 2024-04-01 00:31:32 ┆ 2024-04-01 00:31:32 UTC │
│ E017 ┆ 2024-04-08T10:13:32 ┆ Asia/Seoul ┆ 2024-04-08 10:13:32 ┆ 2024-04-08 01:13:32 UTC │
└─────────┴─────────────────────┴────────────┴─────────────────────┴─────────────────────────┘
E009’s submission was recorded in UTC and appears as 00:31:32 UTC. E017’s 10:13:32 becomes 01:13:32 UTC because it was recorded on a Seoul clock.
All three readings now refer to instants on the same UTC scale. A time difference calculated from these values therefore does not depend on which local clock supplied each original reading.
Zones with clock changes
A source zone does not always make a clock reading unambiguous. When daylight saving time ended in New York on November 3, 2024, clocks went back one hour and read 01:30 twice. The first occurrence was four hours behind UTC and the second was five hours behind.
Polars raises an error by default when asked to assign America/New_York to that reading. A recorded UTC offset would distinguish the two occurrences. Seoul was nine hours ahead of UTC throughout 2024 and had no repeated hour that year. The interpretation of a local reading therefore depends on the zone’s clock rules for its date.
11.4 Ordering observations and defining a previous value
Once observations have an interpretable time order, which earlier value should each one be compared with? In this constructed example, each person has one scheduled prompt per day. Participant p1 reports mood scores of 2, 4 and 7 on days 1, 2 and 4. On day 4, you can compare 7 with the last recorded score, 4. The change since yesterday is unknown because day 3 has no score. The input lists days 4, 1 and 2. Until the rows are in time order within each person, the preceding row need not contain the previous recorded score.
dplyr::arrange() sorts observations by participant and day. With group_by(participant_id), lag() starts over for each person. lag(day) gives the day on the preceding row, and value - lag(value) gives the change since that day. The first row for each person has no predecessor, so both results are NA. ungroup() drops the grouping afterward.
1
2
3
4
5
6
7
8
9
10
11
observations <- tibble(
participant_id = c("p1", "p1", "p1"),
day = c(4L, 1L, 2L),
value = c(7, 2, 4)
)
previous_record <- observations |>
arrange(participant_id, day) |>
group_by(participant_id) |>
mutate(previous_day = lag(day), change = value - lag(value)) |>
ungroup()
previous_record
1
2
3
4
5
6
# A tibble: 3 × 5
participant_id day value previous_day change
<chr> <int> <dbl> <int> <dbl>
1 p1 1 2 NA NA
2 p1 2 4 1 2
3 p1 4 7 2 3
Day 1 has no predecessor. Day 2 compares 4 with 2, and day 4 compares 7 with 4. The difference between day and previous_day gives the length of each comparison in days.
1
previous_record$day - previous_record$previous_day
1
[1] NA 1 2
Day 2’s change of 2 spans one day. Day 4’s change of 3 spans two days because its previous recorded score was on day 2.
After sorting by participant and day, Polars shift() moves the values down one row. .over("participant_id") confines the shift to each person. previous_day identifies the earlier observation, and change gives the current value minus that observation’s value.
1
2
3
4
5
6
7
8
observations = pl.DataFrame(
{"participant_id": ["p1", "p1", "p1"], "day": [4, 1, 2], "value": [7, 2, 4]}
)
previous_record = observations.sort("participant_id", "day").with_columns(
previous_day=pl.col("day").shift().over("participant_id"),
change=(pl.col("value") - pl.col("value").shift()).over("participant_id"),
)
previous_record
1
2
3
4
5
6
7
8
9
10
shape: (3, 5)
┌────────────────┬─────┬───────┬──────────────┬────────┐
│ participant_id ┆ day ┆ value ┆ previous_day ┆ change │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞════════════════╪═════╪═══════╪══════════════╪════════╡
│ p1 ┆ 1 ┆ 2 ┆ null ┆ null │
│ p1 ┆ 2 ┆ 4 ┆ 1 ┆ 2 │
│ p1 ┆ 4 ┆ 7 ┆ 2 ┆ 3 │
└────────────────┴─────┴───────┴──────────────┴────────┘
On day 4, the previous recorded score is from day 2. The three-point increase spans two days.
Previous occasion
To measure change from the scheduled day before each observation, the table needs a row for every scheduled day. Day 3 must therefore appear even though its mood score is missing.
In R, the day-3 row has NA for mood. Once the days are in order within each participant, lag(day) gives the previous scheduled day and lag(value) gives its score, even when that score is missing.
1
2
3
4
5
6
7
8
9
10
11
occasions <- tibble(
participant_id = c("p1", "p1", "p1", "p1"),
day = c(1L, 2L, 3L, 4L),
value = c(2, 4, NA, 7)
)
previous_occasion <- occasions |>
arrange(participant_id, day) |>
group_by(participant_id) |>
mutate(previous_day = lag(day), change = value - lag(value)) |>
ungroup()
previous_occasion
1
2
3
4
5
6
7
# A tibble: 4 × 5
participant_id day value previous_day change
<chr> <int> <dbl> <int> <dbl>
1 p1 1 2 NA NA
2 p1 2 4 1 2
3 p1 3 NA 2 NA
4 p1 4 7 3 NA
Day 4’s predecessor is now day 3. Its change is NA because the previous score is missing. Day 3’s change is also NA because its current score is missing. Day 2 still shows a two-point increase.
In the Polars table, day 3 has its own row with None for mood. After sorting, shift().over("participant_id") now reaches the previous scheduled day even when that day has no score.
1
2
3
4
5
6
7
8
9
10
11
12
occasions = pl.DataFrame(
{
"participant_id": ["p1", "p1", "p1", "p1"],
"day": [1, 2, 3, 4],
"value": [2, 4, None, 7],
}
)
previous_occasion = occasions.sort("participant_id", "day").with_columns(
previous_day=pl.col("day").shift().over("participant_id"),
change=(pl.col("value") - pl.col("value").shift()).over("participant_id"),
)
previous_occasion
1
2
3
4
5
6
7
8
9
10
11
shape: (4, 5)
┌────────────────┬─────┬───────┬──────────────┬────────┐
│ participant_id ┆ day ┆ value ┆ previous_day ┆ change │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞════════════════╪═════╪═══════╪══════════════╪════════╡
│ p1 ┆ 1 ┆ 2 ┆ null ┆ null │
│ p1 ┆ 2 ┆ 4 ┆ 1 ┆ 2 │
│ p1 ┆ 3 ┆ null ┆ 2 ┆ null │
│ p1 ┆ 4 ┆ 7 ┆ 3 ┆ null │
└────────────────┴─────┴───────┴──────────────┴────────┘
On day 4, previous_day is now 3. The score that shift() brings forward from day 3 is null. The three-point increase was from day 2 to day 4. The change from day 3 to day 4 is unknown.
Participant boundaries and ties
A daily comparison also requires knowing whether each day has one observation. The next example adds participant p2, with one observation on day 1 and two on day 2. A count by participant and day identifies the tie.
Sorting the two day-2 rows by observation_id gives a reproducible order within p2’s record. The dates alone cannot tell which observation came first. Grouping by participant also prevents a person’s first observation from being compared with another person’s last one.
1
2
3
4
5
6
7
8
9
10
11
12
13
boundary_cases <- tibble(
observation_id = c("o1", "o2", "o3", "o4", "o5", "o6"),
participant_id = c("p1", "p1", "p1", "p2", "p2", "p2"),
day = c(1L, 2L, 4L, 1L, 2L, 2L),
value = c(2, 4, 7, 5, 8, 6)
)
count(boundary_cases, participant_id, day) |>
filter(n > 1)
boundary_cases |>
arrange(participant_id, day, observation_id) |>
group_by(participant_id) |>
mutate(previous_value = lag(value), change = value - lag(value)) |>
ungroup()
1
2
3
4
5
6
7
8
9
10
11
12
13
# A tibble: 1 × 3
participant_id day n
<chr> <int> <int>
1 p2 2 2
# A tibble: 6 × 6
observation_id participant_id day value previous_value change
<chr> <chr> <int> <dbl> <dbl> <dbl>
1 o1 p1 1 2 NA NA
2 o2 p1 2 4 2 2
3 o3 p1 4 7 4 3
4 o4 p2 1 5 NA NA
5 o5 p2 2 8 5 3
6 o6 p2 2 6 8 -2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
boundary_cases = pl.DataFrame(
{
"observation_id": ["o1", "o2", "o3", "o4", "o5", "o6"],
"participant_id": ["p1", "p1", "p1", "p2", "p2", "p2"],
"day": [1, 2, 4, 1, 2, 2],
"value": [2, 4, 7, 5, 8, 6],
}
)
(
boundary_cases.group_by("participant_id", "day")
.agg(n=pl.len())
.filter(pl.col("n") > 1)
)
boundary_cases.sort("participant_id", "day", "observation_id").with_columns(
previous_value=pl.col("value").shift().over("participant_id"),
change=(pl.col("value") - pl.col("value").shift()).over("participant_id"),
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
shape: (1, 3)
┌────────────────┬─────┬─────┐
│ participant_id ┆ day ┆ n │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ u32 │
╞════════════════╪═════╪═════╡
│ p2 ┆ 2 ┆ 2 │
└────────────────┴─────┴─────┘
shape: (6, 6)
┌────────────────┬────────────────┬─────┬───────┬────────────────┬────────┐
│ observation_id ┆ participant_id ┆ day ┆ value ┆ previous_value ┆ change │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞════════════════╪════════════════╪═════╪═══════╪════════════════╪════════╡
│ o1 ┆ p1 ┆ 1 ┆ 2 ┆ null ┆ null │
│ o2 ┆ p1 ┆ 2 ┆ 4 ┆ 2 ┆ 2 │
│ o3 ┆ p1 ┆ 4 ┆ 7 ┆ 4 ┆ 3 │
│ o4 ┆ p2 ┆ 1 ┆ 5 ┆ null ┆ null │
│ o5 ┆ p2 ┆ 2 ┆ 8 ┆ 5 ┆ 3 │
│ o6 ┆ p2 ┆ 2 ┆ 6 ┆ 8 ┆ -2 │
└────────────────┴────────────────┴─────┴───────┴────────────────┴────────┘
The count shows two records for p2 on day 2. The first row for p2, o4, has no previous value because the calculation starts over for each participant. In identifier order, o5 has a score of 8 and o6 has 6, giving a change of -2. To conclude that mood fell by two points, we would need the observation times or a source rule establishing that o5 came first.