Sampling Random POSIXct Dates & Times in R (Example Code)
In this R tutorial you’ll learn how to draw a random sample of dates and times.
Creation of Example Data
date_seq <- seq(as.POSIXct('2025/01/01'), # Defining date & time sequence as.POSIXct('2028/01/01'), by = "30 mins") head(date_seq) # [1] "2025-01-01 00:00:00 UTC" "2025-01-01 00:30:00 UTC" # [3] "2025-01-01 01:00:00 UTC" "2025-01-01 01:30:00 UTC" # [5] "2025-01-01 02:00:00 UTC" "2025-01-01 02:30:00 UTC" |
date_seq <- seq(as.POSIXct('2025/01/01'), # Defining date & time sequence as.POSIXct('2028/01/01'), by = "30 mins") head(date_seq) # [1] "2025-01-01 00:00:00 UTC" "2025-01-01 00:30:00 UTC" # [3] "2025-01-01 01:00:00 UTC" "2025-01-01 01:30:00 UTC" # [5] "2025-01-01 02:00:00 UTC" "2025-01-01 02:30:00 UTC"
Example: Generate Random Sample of Dates & Times
set.seed(456444564) # Drawing random dates & times date_samp <- sample(date_seq, size = 100, replace = TRUE) head(date_samp) # [1] "2025-02-12 07:00:00 UTC" "2025-05-13 07:30:00 UTC" # [3] "2025-01-22 20:00:00 UTC" "2027-10-22 07:30:00 UTC" # [5] "2026-12-17 12:00:00 UTC" "2027-06-15 20:30:00 UTC" |
set.seed(456444564) # Drawing random dates & times date_samp <- sample(date_seq, size = 100, replace = TRUE) head(date_samp) # [1] "2025-02-12 07:00:00 UTC" "2025-05-13 07:30:00 UTC" # [3] "2025-01-22 20:00:00 UTC" "2027-10-22 07:30:00 UTC" # [5] "2026-12-17 12:00:00 UTC" "2027-06-15 20:30:00 UTC"