0

I am struggling to get date/time values converted. The issue is that the time component contains fractional seconds, and there are additional characters in the string that should be filtered out.

The format is of the current data/time variable is:

2018-12-30T18:03:23.400Z

The result I am looking for is:

2018-12-30 18:03:23.4

I have tried reproducing from these stack overflow questions: Parse string with additional characters in format to Date and Convert a large character string to dates, but the dates have a non numeric character

But I haven't been able to get them to work.

CardCape
  • 3
  • 3
  • does the resullt have to be of a specific class? – Onyambu Oct 24 '22 at 21:07
  • Ideally I would like it to be either POSIXlt or POSIXct, but from my understanding neither of those are able to handle fractions of seconds. If that is the case then I am not sure what class would work best. – CardCape Oct 24 '22 at 21:12

1 Answers1

2

The anytime package (which I wrote) aims to take the pain out of date (and datetime) parsing. It covers your format (with the one caveat about the incoming timezone which few parsers cover) as it does cover others:

> library(anytime)
> anytime("2018-12-30T18:03:23.400Z")
[1] "2018-12-30 18:03:23.4 CST"
> 

If you want just one digit shown, select that explicitly. I tell my R sessions to default to six:

> Sys.time()
[1] "2022-10-24 16:41:34.745706 CDT"
> options(digits.secs=1)
> Sys.time()
[1] "2022-10-24 16:41:49.9 CDT"
> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • 1
    Thanks for pointing to the `digits.secs` option . Never used it before – Onyambu Oct 24 '22 at 21:43
  • 1
    My pleasure! Date and datetime functions are actually quite complete and performant in (base) R. But as with a few other things, it is not always evident where to find. Reading other people's code, and lurking on places like this or some mailing lists can help. – Dirk Eddelbuettel Oct 24 '22 at 21:44
  • My pleasure, and welcome to StackOverflow! As you appear to be new here, allow me to suggest that you 'accept the answer' (click on the tickmark, this distributes karma to me but also gives you karma as accepting an answer that works is a good thing) and/or 'upvote the answer' (click on the up triangle, this may require more than 10 points as I recall). – Dirk Eddelbuettel Oct 24 '22 at 23:18