3

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

thelatemail
  • 91,185
  • 12
  • 128
  • 188
Karthick
  • 357
  • 4
  • 13

2 Answers2

6

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)

Community
  • 1
  • 1
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • `POSIXt` is a virtual class, so you can't actually use `POSIXt` directly. – Joshua Ulrich Jan 29 '15 at 06:13
  • @JoshuaUlrich That's by convention only, right? R doesn't have a way to specify/enforce a virtual class (despite what the `?DateTimeClasses` page says) – MrFlick Jan 29 '15 at 06:16
  • Right, you can make a `POSIXt` object `p <- structure(1405833110, class="POSIXt", tzone="GMT")`, but I doubt you would be able to do much with it. – Joshua Ulrich Jan 29 '15 at 14:09
2

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
Aurèle
  • 12,545
  • 1
  • 31
  • 49