Christian R. Houen
Christian R. Houen

Reputation: 89

Converting seconds from specific time on a specific date in R

If this question has been asked before, please downvote and direct me. I have been looking through SO, but it seems no one has had the need for a non-midnight start time i.e. everyone wants to know how to convert seconds from a specific midnight value.

I'm trying to convert my second values to a data value. What I have are seconds from the time 2017-05-21 22:00.

I tried using the as.POSIXct() function, however it only seem to take Y-m-d into account and disregards if I write h:m after it.

e.g file$date = as.POSIXct(file$Time,origin = "2017-05-21 22:00") gives me

  Time         date
1 0.00         2017-05-22 00:00:00

I have found if I use

file$Time = file$Time-3600*4

file$date = as.POSIXct(file$Time,origin = "2017-05-22")

for some reason gives me the correct output which is of course

  Time         date
1 0.00         2017-05-21 22:00:00

Any idea on how to do this more elegantly?

Also, if you have a clue on why that gives me the correct output, I'm all ears.

Upvotes: 0

Views: 749

Answers (2)

MKR
MKR

Reputation: 20095

You can simply try as.POSIXct to convert your starting time and then keep on adding seconds. as:

as.POSIXct("2017-05-21 22:00:00", format = "%Y-%m-%d %H:%M:%S")
#[1] "2017-05-21 22:00:00 BST"
 as.POSIXct("2017-05-21 22:00:00", format = "%Y-%m-%d %H:%M:%S") + 1
#[1] "2017-05-21 22:00:01 BST"
 as.POSIXct("2017-05-21 22:00:00", format = "%Y-%m-%d %H:%M:%S") + 100
#[1] "2017-05-21 22:01:40 BST"
 as.POSIXct("2017-05-21 22:00:00", format = "%Y-%m-%d %H:%M:%S") + 300
#[1] "2017-05-21 22:05:00 BST

You can even specify time-zone using tz parameter as:

as.POSIXct("2017-05-21 22:00:00", tz = "UTC", format = "%Y-%m-%d %H:%M:%S")
#[1] "2017-05-21 22:00:00 UTC"

as.POSIXct("2017-05-21 22:00:00", tz = "UTC", format = "%Y-%m-%d %H:%M:%S") + 96
#[1] "2017-05-21 22:01:36 UTC"

Upvotes: 1

drmariod
drmariod

Reputation: 11802

Have a look at lubridate...

library(lubridate)
ymd_hm("2017-05-21 22:00") + seconds(1.01)

So in your case it would be something like

file$date <- ymd_hm("2017-05-21 22:00") + seconds(file$Time) 

Upvotes: 0

Related Questions