I have a dataframe which contains a variable called DateTime
with data about date and time. Below I show an example:
df<- data.frame(DateTime=c("2016-08-23 00:22:23","2016-08-23 00:26:38","2016-08-23 01:04:12","2016-08-23 02:27:58","2016-08-23 03:04:31","2016-08-23 04:51:46"))
df$DateTime<- as.POSIXct(df$DateTime, format="%Y-%m-%d %H:%M:%S", tz="UTC")
df
DateTime
1 2016-08-23 00:22:23
2 2016-08-23 00:26:38
3 2016-08-23 01:04:12
4 2016-08-23 02:27:58
5 2016-08-23 03:04:31
6 2016-08-23 04:51:46
I want to create a variable called DateTime45
that rounds up those to dates and times at 45-minutes intervals. Below I show what I tried so far:
df$DateTime45<- round_date(df$DateTime, "45 mins")
df
DateTime DateTime45
1 2016-08-23 00:22:23 2016-08-23 00:00:00
2 2016-08-23 00:26:38 2016-08-23 00:45:00
3 2016-08-23 01:04:12 2016-08-23 01:00:00
4 2016-08-23 02:27:58 2016-08-23 02:45:00
5 2016-08-23 03:04:31 2016-08-23 03:00:00
6 2016-08-23 04:51:46 2016-08-23 04:45:00
However, as you can see, it creates something strange since time intervals are not evenly distributed. I would like to get this instead:
df
DateTime DateTime45
1 2016-08-23 00:22:23 2016-08-23 00:00:00
2 2016-08-23 00:26:38 2016-08-23 00:45:00
3 2016-08-23 01:04:12 2016-08-23 00:45:00
4 2016-08-23 02:27:58 2016-08-23 02:15:00
5 2016-08-23 03:04:31 2016-08-23 03:00:00
6 2016-08-23 04:51:46 2016-08-23 04:30:00
The limits of a 45-time-intervals would be the following if we consider the time in 24-hour format:
TimeIntervalLimits<- seq.POSIXt(as.POSIXct("2016-08-23 00:00:00"), as.POSIXct("2016-08-24 00:45:00"), by = "45 min", format="%Y-%m-%d %H-%M-%S", tz="UTC")
TimeIntervalLimits<- as.data.frame(TimeIntervalLimits)
TimeIntervalLimits
TimeIntervalLimits
1 2016-08-23 00:00:00
2 2016-08-23 00:45:00
3 2016-08-23 01:30:00
4 2016-08-23 02:15:00
5 2016-08-23 03:00:00
6 2016-08-23 03:45:00
7 2016-08-23 04:30:00
8 2016-08-23 05:15:00
9 2016-08-23 06:00:00
10 2016-08-23 06:45:00
11 2016-08-23 07:30:00
12 2016-08-23 08:15:00
13 2016-08-23 09:00:00
14 2016-08-23 09:45:00
15 2016-08-23 10:30:00
16 2016-08-23 11:15:00
17 2016-08-23 12:00:00
18 2016-08-23 12:45:00
19 2016-08-23 13:30:00
20 2016-08-23 14:15:00
21 2016-08-23 15:00:00
22 2016-08-23 15:45:00
23 2016-08-23 16:30:00
24 2016-08-23 17:15:00
25 2016-08-23 18:00:00
26 2016-08-23 18:45:00
27 2016-08-23 19:30:00
28 2016-08-23 20:15:00
29 2016-08-23 21:00:00
30 2016-08-23 21:45:00
31 2016-08-23 22:30:00
32 2016-08-23 23:15:00
33 2016-08-24 00:00:00
. . .
. . .
Does anyone know how to get the variable DateTime45
in the way I want it?
Thanks in advance