Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

r - Current time in ISO 8601 format

For logging purposes, how can an R script get the current date and time, in the UTC time zone, as an ISO 8601 string in this format:

2015-12-31T14:26:56.600374+00:00

as.POSIXlt seems to be the solution, and the documentation claims that it accepts a format parameter, but I can't make that work (on R version 3.1.3):

> as.POSIXlt(Sys.time(), "UTC", "%Y-%m-%dT%H:%M:%S")
[1] "2015-04-08 14:37:58 UTC"
> as.POSIXlt(Sys.time(), tz="UTC", format="%Y-%m-%dT%H:%M:%S")
[1] "2015-04-08 14:38:02 UTC"
> as.POSIXct(Sys.time(), tz="UTC", format="%Y-%m-%dT%H:%M:%S")
[1] "2015-04-08 11:38:22 BRT"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

as.POSIXlt (and as.POSIXct) are for input. Use either format or strftime for output. See ?strftime for details on format strings:

 tm <- as.POSIXlt(Sys.time(), "UTC")
 strftime(tm , "%Y-%m-%dT%H:%M:%S%z")
#[1] "2015-04-08T15:11:22+0000"

The third parameter of as.POSIXlt, format, is used when the first parameter is a string-like value that needs to be parsed. Since we are passing in a Date value from Sys.time, the format is ignored.

I don't think that the colon in the timezone output is requirement of the ISO 8601 format but I could be wrong on that point. The help page says the standard is POSIX 1003.1. May need to put in the colon with a regex substitution if needed.

After looking at http://dotat.at/tmp/ISO_8601-2004_E.pdf I see that there is no colon in the "basic" format" timezone representation, but there is one in the "extended format".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...