2

I am struggling to make a sequence of timestamps in a dataframe from one time to another with milliseconds. I can do this easily with seconds but I am running into problems when using milliseconds.

options(digits.secs=1)
Time1 = "2018-06-26 14:12:00.0"
Time2 = "2018-06-28 14:34:00.0"

Time1 <- as.POSIXct(Time1 , format = "%Y-%m-%d %H:%M:%OS",tz = "UTC")
Time2 <- as.POSIXct(Time2 , format = "%Y-%m-%d %H:%M:%OS",tz = "UTC")

df <- data.frame(DateTime = as.character(seq.POSIXt(Time1,Time2,units = "milliseconds", by = 1)))

This returns just a sequence of seconds:

1   2018-06-26 14:12:00
2   2018-06-26 14:12:01
3   2018-06-26 14:12:02
4   2018-06-26 14:12:03
5   2018-06-26 14:12:04

I also tried an altered version of this post Create a series of timestamps along milliseconds in R:

df <- data.frame(DateTime = as.character(seq.POSIXt(Time1, Time2, units = "seconds", by = .1)))

This returns a strange sequence:

1   2018-06-26 14:12:00.0
2   2018-06-26 14:12:00.0
3   2018-06-26 14:12:00.2
4   2018-06-26 14:12:00.2
5   2018-06-26 14:12:00.4
6   2018-06-26 14:12:00.5

What I am trying to create:

1   2018-06-26 14:12:00.0
2   2018-06-26 14:12:00.1
3   2018-06-26 14:12:00.2
4   2018-06-26 14:12:00.3
5   2018-06-26 14:12:00.4
6   2018-06-26 14:12:00.5
...
...
megmac
  • 547
  • 2
  • 11

1 Answers1

1

Basically you need to have your length.out, per case. So, using this very helpful extract_number_from_string, using difftime I put Time2_POS before Time1_POS, to get a positive return we take:

dif_T2_T1 <- difftime(Time2_POS, Time1_POS, units = 'secs')
pattern <- '(\\d)+'
as.numeric(str_extract(dif_T2_T1, pattern = pattern))
[1] 174120

fair enough, but we need ten times more:

as.numeric(str_extract(dif_T2_T1, pattern = pattern)) * 10
[1] 1741200

df  <- data.frame(Date_Time = as.character(seq.POSIXt(Time1_POS, Time2_POS, units = 'seconds', length.out = 1741200)))

which gives us:

df3$Date_Time[1:20]
 [1] 2018-06-26 14:12:00.0 2018-06-26 14:12:00.1 2018-06-26 14:12:00.2 2018-06-26 14:12:00.3
 [5] 2018-06-26 14:12:00.4 2018-06-26 14:12:00.5 2018-06-26 14:12:00.6 2018-06-26 14:12:00.7
 [9] 2018-06-26 14:12:00.8 2018-06-26 14:12:00.9 2018-06-26 14:12:01.0 2018-06-26 14:12:01.1
[13] 2018-06-26 14:12:01.2 2018-06-26 14:12:01.3 2018-06-26 14:12:01.4 2018-06-26 14:12:01.5
[17] 2018-06-26 14:12:01.6 2018-06-26 14:12:01.7 2018-06-26 14:12:01.8 2018-06-26 14:12:01.9
1741200 Levels: 2018-06-26 14:12:00.0 2018-06-26 14:12:00.1 ... 2018-06-2  14:34:00.0

HTH

Chris
  • 1,647
  • 1
  • 18
  • 25