creating a non-standard repeating datetime series in R

Viewed 23

My objective is to use R (or potentially python) to create a datetime series for 3 non-standard work shifts (A, B, C) in order to link those shifts to datetime events in another table. The basic pattern is 3 24-hour alternating on/off periods followed by a 96 hour off period. Each shift begins and ends at 08:00.

The calendar pattern for each shifts looks something like this

(carryover) A (1, 3) A (8, 10, 12, 17, 19...) B (2, 4, 6, 11, 13...) C (5, 7, 9, 14, 16...)

I have two main problems:

  • the primary problem is creating a loop that replicates the 3 on/off datetime series over a year-long period for each shift.
  • the secondary problem is the size of the table: because the shifts cross midnight of the following day, I'm stuck on how to link the date-time events without resorting to a seconds table (which seems unwieldy). My first thought was using a different time-zone (my tz - 8 hours) but I'm working with US MST, so it seems I don't have enough westward TZ to work with.

Here's what I have so far... any help is greatly appreciated

library(lubridate)

# create beginning and end dates for each sequence: A, B, C)

st_A <- as.POSIXct("2022-01-08 08:00:00")
stp_A <- as.POSIXct("2022-12-30 08:00:00")

st_B <- as.POSIXct("2022-01-02 08:00:00")
stp_B <- as.POSITXct("2022-12-31 08:00:00")

st_C <- as.POSIXct("2022-01-05 08:00:00")
stp_C <- as.POSIXct("2023-01-01 08:00:00")



# A_carryover (1, 3) (required for carryover from previous calender) 

A_carryover <- as.POSIXct("2022-01-01 08:00:00")
interval_1 <- A_initial + c(0:86399) * seconds(1)
interval_2 <- A_initial + c(172800:259199) * seconds(1)
A_carryover <- as.data.frame(c(interval_1, interval_2))
A_carryoverl$shift <- "A"
names(A_carryoverl)[1] <- 'datetime'


# create sequence of 3 day-long second intervals from 08:00 to 08:00

interval_1 <- st_A + c(0:86399) * seconds(1)
interval_2 <- st_A+ c(172800:259199) * seconds(1)
interval_3 <- st_A + c(345599:431999) * seconds(1)

[...add 345000 seconds and repeat until stp_A]

# combine all intervals into dataframe 
df_A <- as.data.frame(c(interval_1, interval_2, interval_3))
df_A$shift <- "A"
names(df_A)[1] <- 'datetime'

[... repeat for st_B, and st_C]

[... combine series into one dataframe, with each shift identified]

df_all <- rbind(A_carryover, df_A, df_B, df_C)

0 Answers
Related