Stephen Clark
Stephen Clark

Reputation: 596

Add a day to a date AND time string

I would like to advance a date and time string in R by one day, keeping the time.

datetime<-"2015-07-20T16:33:59.158Z"

as.Date(datetime)+1
as.POSIXct(datetime)+24*60*60

library(lubridate)
as.POSIXct(datetime)+days(1)
as.POSIXct(datetime)+hours(24)

All return either

 "2015-07-21"
 "2015-07-21 BST"

when what is required is

"2015-07-21T16:33:59.158Z"

Thanks.

Upvotes: 1

Views: 520

Answers (3)

akrun
akrun

Reputation: 887531

We can use anytime

library(anytime)
anytime(datetime) + 24 * 60 * 60
#[1] "2015-07-21 16:33:59 EDT"

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389155

Check the output for

as.POSIXct(datetime)
#[1] "2015-07-20"

it truncates the time component. You need to specify proper format to it since it is not in standard format.

as.POSIXct(datetime, format = "%Y-%m-%dT%H:%M:%OS")
#[1] "2015-07-20 16:33:59

Once you do that you can do

as.POSIXct(datetime, format = "%Y-%m-%dT%H:%M:%OS") + 24*60*60
#[1] "2015-07-21 16:33:59"

Upvotes: 3

Sonny
Sonny

Reputation: 3183

You can do as below:

library(lubridate)
datetime <- ymd_hms("2015-07-20T16:33:59.158Z")
datetime + 24*60*60
[1] "2015-07-21 16:33:59 UTC"

Upvotes: 3

Related Questions