Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert exact Sys.time() output to string / character in R?

Tags:

r

How can we get the exact printed output of Sys.time() (e.g. "2020-01-14 17:21:31 AEDT") as a string / character vector?

Background

The output of my Sys.time() is

[1] "2020-01-14 17:21:31 AEDT"

the dput() of which is

structure(1578982891.74164, class = c("POSIXct", "POSIXt"))

In the console, it looks like it might be of class character, but as we can see from the dput (or by calling class()) it isn't

structure(1578982891.74164, class = c("POSIXct", "POSIXt")) %>% class()
[1] "POSIXct" "POSIXt" 

The exact output I am after is "2020-01-14 17:21:31 AEDT", where "2020-01-14 17:21:31 AEDT" %>% class is character.

Also note: I would like to not use external packages for this

What I've tried so far

The obvious thing to try, Sys.time() %>% as.character, removes the characters at the end (AEDT in this case), which is not not desired here

like image 392
stevec Avatar asked Dec 18 '22 14:12

stevec


1 Answers

One option would be to use format(), which can take Sys.time() as input and generate a character output:

format(Sys.time(), "%Y-%m-%d %H:%M:%S %Z")

[1] "2020-01-14 07:40:06 CET"
like image 58
Tim Biegeleisen Avatar answered Feb 12 '23 20:02

Tim Biegeleisen