2

I have a character vector like below which hold time in the format HH:MM:SS.sss such that it can be used for time series analysis in a dataframe

x <- "05:17:55.703"

I wanted to convert it into timestamp with milliseconds without date and timezone - is this even possible ?

What have I tried ->

> as.POSIXct("05:17:55.703",format = "%H:%M:%OS")
[1] "2019-09-19 05:17:55 IST"
Issue is that, it doesn't show the milliseconds part and shows the date and timezone which I would like to avoid

> as.POSIXlt("05:17:55.703",format = "%H:%M:%OS")
[1] "2019-09-19 05:17:55 IST"
Issue is that, it doesn't show the milliseconds part and shows the date and timezone which I would like to avoid

> as.POSIXlt("05:17:55.703",format = "%H:%M:%S.%OS")
[1] "2019-09-19 05:17:55 IST"
Issue is that, it doesn't show the milliseconds part and shows the date and timezone which I would like to avoid

> strptime("05:17:55.703", "%H:%M:%OS")
[1] "2019-09-19 05:17:55 IST"
Issue is that, it doesn't show the milliseconds part and shows the date and timezone which I would like to avoid
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user3206440
  • 4,749
  • 15
  • 75
  • 132
  • 1
    Datetime objects must contain a date. However, I wonder why you care what is *shown*. The actual values should matter much more to you. – Roland Sep 19 '19 at 07:22

3 Answers3

2

You can consider to use hms from lubridate which will return a "Period" object

lubridate::hms(x)
#[1] "5H 17M 55.703S"

This shows millisecond part without date and timezone.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

Another option is the hms package:

hms::as_hms("05:17:55.703")
#> 05:17:55.703

Created on 2019-09-19 by the reprex package (v0.3.0)

Mikko Marttila
  • 10,972
  • 18
  • 31
0

You could use as.POSIXct("05:17:55.703",format = "%H:%M:%OS") and options(digits.sec = 3). This should give "2022-03-28 05:17:55.703 CEST"

as.POSIXct("05:17:55.703",format = "%H:%M:%OS")
options(digits.sec = 3)
#  "2022-03-28 05:17:55.703 CEST"
Christian
  • 243
  • 1
  • 8