Create a series of timestamps along milliseconds in R
Asked Answered
H

2

1

I have start date as "2017-11-14 10:11:01 CET" and end date as "2017-11-15 01:15:59 CET". I want to create timestamps of 500 milliseconds each, between these start and end timestamps. E.g. I need a dataframe containing the following output

timestamp
2017-11-14 10:11:01.000
2017-11-14 10:11:01.500
2017-11-14 10:11:02.000
2017-11-14 10:11:02.500
.
.
.
2017-11-15 01:15:59.000

Somehow, I managed to get the start and end date in milliseconds using the following code:

start.date <- strptime("2017-11-14 10:11:01 CET", "%Y-%m-%d %H:%M:%OS")
start.date <- format(start.date, "%Y-%m-%d %H:%M:%OS3")
Output: "2017-11-14 10:11:01.000"

Similarly, I got end date as 2017-11-15 01:15:59.000. I now want to use sequence function to create sequence of timestamps each of 500 milliseconds. I did something like

seq.POSIXt(as.POSIXct(start), as.POSIXct(end), units = "milliseconds", by = 500)

but it created a series of 20 seconds. e.g.,

"2017-11-14 10:11:01 CET" 
"2017-11-14 10:19:21 CET" 
"2017-11-14 10:27:41 CET"
.
.
.
"2017-11-15 01:11:01 CET"

Once, I am able to get this series, I further want to convert it into UNIX timestamps. Can someone help me to resolve this issue?

Hulen answered 10/8, 2018 at 14:27 Comment(0)
E
2

I don't know if this is what you are looking for but it seems to be working

seq.POSIXt(as.POSIXct(start), as.POSIXct(end), units = "seconds", by = .5)
Emulation answered 10/8, 2018 at 14:40 Comment(3)
It gives correct series but I am not able to further convert them into UNIX timestamp. E.g. If I have something like "2017-11-14 11:34:19.5 CET", then its UNIX conversion rounds of the .5 seconds and gives me "2017-11-14 11:34:20 CET". For Unix conversion I am using following: as.numeric (as.POSIXct("2017-11-14 11:34:19.500"), tz = "GMT", origin = "1970-01-01")Hulen
I am simply using POSIXct dates now. Thanks anyways :)Hulen
seq.POSIXt() doesn't have an argument named units, so units = "seconds" will be ignored and make no sense.Solipsism
E
0

When you use the function as.integer it will get rid of the decimal part of the number, in your case, the milliseconds.

I suggest you to use this workaround to get the number desired in UNIX format. In order to get the desired output you can take the output of the function as.integer and then attach at the end what you need. Since your UNIX timestamps will only have the last three digits equal to 000 or 500 you can try:

k<-as.numeric(seq.POSIXt(as.POSIXct(start.date), as.POSIXct(stop.date), units = "seconds", by = .5))[1:4]


k1<-cbind(substr(as.character(k), 1, 10),c("000","500"))

as.numeric(paste0(k1[,1],k1[,2]))
[1] 1510650661000 1510650661500 1510650662000 1510650662500

Notice that I am doing this only to the first 4 elements of the vector, but the logic remains the same.

Emulation answered 10/8, 2018 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.