Josh
Josh

Reputation: 1337

Extracting time from Sys.time

I have a question that I think stems from my lack of understanding about the nature of the Sys.time() output. I want to save output from R with a timestamp in the filename. I tried using %>% and gsub() but didn't get the expected result.

When I run Sys.time, this is output:

Sys.time()
[1] "2018-07-02 21:57:27 CDT"

When I run the code I think should work, this happens:

> Sys.time() %>% gsub("^[^\\s]+\\s([^\\s]+)\\s[^\\s]+$", "\\1", .)
[1] "2018-07-02 21:57:27"

Interestingly, this code yields the value I want:

> Sys.time() %>% gsub("^[^\\s]+\\s", "", .)
[1] "21:57:27"

Any ideas what I'm doing wrong?

Upvotes: 2

Views: 828

Answers (1)

Josh
Josh

Reputation: 1337

@akrun, thank you, that works!

I also realized the issue. Even though Sys.time() prints "2018-07-02 21:57:27 CDT" that's just formatting. "2018-07-02 22:16:45" is the actual character string.

> as.character(Sys.time())
[1] "2018-07-02 22:16:45"

This also explains why my second gsub() code worked, since there is only one whitespace character in the Sys.time() output.

> Sys.time() %>% gsub("^[^\\s]+\\s", "", .)
[1] "21:57:27"

Upvotes: 3

Related Questions