Current time in ISO 8601 format

独自空忆成欢 提交于 2019-11-27 04:43:16

问题


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"

回答1:


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", "%Y-%m-%dT%H:%M:%S")
 strftime(tm , "%Y-%m-%dT%H:%M:%S%z")
#[1] "2015-04-08T15:11:22+0000"

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".




回答2:


The package parsedate recognizes and parses Dates in various formats, including all ISO 8601 Formats:

format_iso_8601(Sys.time())
# [1] "2017-09-01T10:59:22+00:00"


来源:https://stackoverflow.com/questions/29517896/current-time-in-iso-8601-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!