I have a date and time column which follows 24 hour format. Now I want it to shift it by 6 hours, such that 6 am of the current day becomes 00:00 and the day completes on 6 am of the following day. In excel, if we subtract 0.25 from the date column, it directly shifts the dates by 6 hours. But similar functionality doesn't seem to work in R. How does one achieve this in R?
Asked
Active
Viewed 1,951 times
1
-
could you share some of your data, eg paste some of it using `dput` (to make your example [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610)) ? – Vincent Bonhomme Apr 22 '16 at 07:47
-
DateTime 2/10/2016 19:18 2/10/2016 19:15 2/10/2016 19:12 2/10/2016 19:09 2/10/2016 19:06 2/10/2016 19:03 Updated 2/10/2016 13:18 2/10/2016 13:15 2/10/2016 13:12 2/10/2016 13:09 2/10/2016 13:06 2/10/2016 13:03 – Girish U R Apr 22 '16 at 07:52
2 Answers
2
You should provide more information on your question, like the data you're using.
To replicate that with R, you could use the lubridate package :
library(lubridate)
new_time <- time - hms("06:00:00")
Hope this helps

cyrilb38
- 924
- 6
- 17
2
A solution using base R. By default arithmetic operations add seconds, so:
now <- Sys.time() #gets the current time
now
"2016-04-22 09:52:21 CEST"
now + 6*3600
"2016-04-22 15:52:21 CEST"
With your data, you can try, around strptime
:
df <- read.table(text="
DateTime
2/10/2016 19:18
2/10/2016 19:15
2/10/2016 19:12
2/10/2016 19:09
2/10/2016 19:06
2/10/2016 19:03", sep=";", h=T)
df
DateTime
1 2/10/2016 19:18
2 2/10/2016 19:15
3 2/10/2016 19:12
4 2/10/2016 19:09
5 2/10/2016 19:06
6 2/10/2016 19:03
df$NewTime <- strptime(as.character(df$DateTime), format="%d/%m/%Y %H:%M") 6*3600
df
DateTime NewTime
1 2/10/2016 19:18 2016-10-03 01:18:00
2 2/10/2016 19:15 2016-10-03 01:15:00
3 2/10/2016 19:12 2016-10-03 01:12:00
4 2/10/2016 19:09 2016-10-03 01:09:00
5 2/10/2016 19:06 2016-10-03 01:06:00
6 2/10/2016 19:03 2016-10-03 01:03:00
You could remove the as.character
step with stringsAsFactors = FALSE
in read.table
.
Does it solve your problem?

Vincent Bonhomme
- 7,235
- 2
- 27
- 38