Search code examples
rposixctdifftime

How to add time (not minutes/seconds etc, just time E.g., 17:30:00) for one particular day to a list of POSIXct dates in R?


I have a data that consists of date and time which are in POSIXct format as shown below :

> DayandTime
             date_time
1  2015-10-01 11:13:25
2  2015-10-01 12:38:09
3  2015-10-01 17:12:00
4  2015-10-02 11:44:05
5  2015-10-05 13:45:07
6  2015-10-05 14:53:31
7  2015-10-06 11:54:54
8  2015-10-06 16:29:22
9  2015-10-06 18:30:46
10 2015-10-07 08:41:35
11 2015-10-07 09:02:12
12 2015-10-07 10:50:25
13 2015-10-07 11:29:25
14 2015-10-07 11:49:22
15 2015-10-07 13:35:27
16 2015-10-07 15:01:17
17 2015-10-08 11:02:12
18 2015-10-08 12:03:50
19 2015-10-08 14:24:16
20 2015-10-08 14:28:31

For every day, I need to add 17.30 as the close time or end_time - on one particular day. Eg., For 01 October, 2015, the end time is October, 2015 17:30:00

The sample output is shown below :

             date_time                   end_time
1  2015-10-01 11:13:25        2015-10-01 17:30:00
2  2015-10-01 12:38:09        2015-10-01 17:30:00
3  2015-10-01 17:12:00        2015-10-01 17:30:00
4  2015-10-02 11:44:05        2015-10-02 17:30:00
5  2015-10-05 13:45:07        2015-10-05 17:30:00
6  2015-10-05 14:53:31        2015-10-05 17:30:00
7  2015-10-06 11:54:54        2015-10-06 17:30:00
8  2015-10-06 16:29:22        2015-10-06 17:30:00
9  2015-10-06 18:30:46        2015-10-06 17:30:00
10 2015-10-07 08:41:35        2015-10-07 17:30:00
11 2015-10-07 09:02:12        2015-10-07 17:30:00
12 2015-10-07 10:50:25        2015-10-07 17:30:00
13 2015-10-07 11:29:25        2015-10-07 17:30:00
14 2015-10-07 11:49:22        2015-10-07 17:30:00
15 2015-10-07 13:35:27        2015-10-07 17:30:00
16 2015-10-07 15:01:17        2015-10-07 17:30:00
17 2015-10-08 11:02:12        2015-10-08 17:30:00
18 2015-10-08 12:03:50        2015-10-08 17:30:00
19 2015-10-08 14:24:16        2015-10-08 17:30:00
20 2015-10-08 14:28:31        2015-10-08 17:30:00

Adding hours or minutes or seconds to each element sounds simple but the results are not the way they are expected to be.


structure(list(date_time = structure(c(1443678205, 1443683289, 
1443699720, 1443766445, 1444032907, 1444037011, 1444112694, 1444129162, 
1444136446, 1444187495, 1444188732, 1444195225, 1444197565, 1444198762, 
1444205127, 1444210277, 1444282332, 1444286030, 1444294456, 1444294711
), class = c("POSIXct", "POSIXt"), tzone = "")), .Names = "date_time", row.names = c(NA, 
-20L), class = "data.frame")

Solution

  • How about this

    Convert Datetime into Date and then Concat the required time:

    DayandTime$end_time <- as.POSIXct(paste(as.Date(as.POSIXct(DayandTime$date_time)), '17:30:00'))