问题
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?
回答1:
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)
回答2:
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.
来源:https://stackoverflow.com/questions/51788662/create-a-series-of-timestamps-along-milliseconds-in-r