date is not changing though time cross midnight using as.POSIXct in r

Viewed 77

I have tried in this way to convert fraction number to date time

daytime = c("0.999259259259259", "0.000162037037037037","0.00106481481481481")

as.POSIXct(as.numeric((daytime)) * 24 * 60 * 60, origin = "2019-08-02 ", tz="GMT")

I am getting

"2019-08-02 23:58:56 GMT"  
"2019-08-02 00:00:14 GMT"  
"2019-08-02 00:01:32 GMT"  

But I should get

"2019-08-02 23:58:56 GMT"  
"2019-08-03 00:00:14 GMT"   
"2019-08-03 00:01:32 GMT"

daytime is too large. I use 3 values for example here. I am looking for suggestions. Thanks in advance.

1 Answers

You can use diff() to identify when to enter a new day.

daytime = c("0.999259259259259", "0.000162037037037037","0.00106481481481481")
daytime <- as.numeric(daytime)

(new_day <- cumsum(c(F, diff(daytime) < 0)))
# [1] 0 1 1

as.POSIXct((daytime + new_day) * 24 * 60 * 60, "GMT", origin = "2019-08-02")

# [1] "2019-08-02 23:58:56 GMT"
# [2] "2019-08-03 00:00:14 GMT"
# [3] "2019-08-03 00:01:32 GMT"
Related