stevec
stevec

Reputation: 52228

Convert exact Sys.time() output to string / character in 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

Upvotes: 8

Views: 3778

Answers (2)

MichaelChirico
MichaelChirico

Reputation: 34703

Tim gives the canonical answer -- you should know of & be familiar with format's method for Date and POSIXt classes. Be sure to read ?strptime regularly.

Note that as.character(Sys.time()) will use the POSIXt method of as.character, which is actually just a simple wrapper for format:

print(as.character.POSIXt)
# function (x, ...) 
# format(x, ...)
# <bytecode: 0x7fbb67f28b20>
# <environment: namespace:base>

So you could actually use as.character if that feels more natural to you; the easiest way would be to simply add usetz = TRUE:

as.character(Sys.time(), usetz = TRUE)
# [1] "2020-01-14 15:22:12 +08"

You can also use the tz argument for finer control over the time zone:

as.character(Sys.time(), tz = 'Asia/Jakarta', usetz = TRUE)
# [1] "2020-01-14 14:25:47 WIB"

Upvotes: 7

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520918

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"

Upvotes: 12

Related Questions