Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert time stamp string "2014-07-20T05:11:49.988Z" into POSIXt in R?

Tags:

timestamp

r

How to convert time stamp string “2014-07-20T05:11:49.988Z” into POSIXt in R?

I want to know why the second is represented in 3 decimel places? also what is the meaning of appending the 'Z' at the end of time stamp? Can anybody know how this string can be converted into time in R

like image 311
Karthick Avatar asked Oct 14 '25 03:10

Karthick


2 Answers

The "Z" is shorthand for UTC. You can parse this in base R with

x <- as.POSIXct("2014-07-20T05:11:49.998Z", 
    format="%Y-%m-%dT%H:%M:%OSZ", tz="GMT")

Note that you generally either use POSIXct or POSIXlt rather than POSIXt directly (both have POSIXt as a base class)

like image 76
MrFlick Avatar answered Oct 19 '25 14:10

MrFlick


The lubridate package has very robust parsers that I tend to prefer over manual specification of the format in base R

library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following object is masked from 'package:base':
#> 
#>     date

(t <- ymd_hms("2014-07-20T05:11:49.998Z"))
#> [1] "2014-07-20 05:11:49 UTC"

Created on 2019-03-11 by the reprex package (v0.2.1)

Making sure that the milliseconds that aren't printed aren't lost either:

second(t)
#> [1] 49.998
like image 31
Aurèle Avatar answered Oct 19 '25 13:10

Aurèle