Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current time in ISO 8601 format

Tags:

r

iso8601

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"
like image 885
Fernando Correia Avatar asked Apr 08 '15 14:04

Fernando Correia


People also ask

How do I format a date in ISO 8601?

ISO 8601 Formats ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

How do I convert datetime to ISO 8601?

toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss.

Is ISO 8601 always UTC?

Date.prototype.toISOString() The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .

Does ISO 8601 include timezone?

Time zone designators. Time zones in ISO 8601 are represented as local time (with the location unspecified), as UTC, or as an offset from UTC.


1 Answers

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

like image 75
IRTFM Avatar answered Sep 24 '22 02:09

IRTFM