1
votes

There is a timestamp variable (i.e. UTC) in my data frame which is a character / string and the date-time format is as follows:-

Fri Aug 10 04:42:47 +0000 2012

How to convert it into a date-time object in R? I tried using the following but it is giving me NAs.

data1$datetime <- as.POSIXct(as.numeric(data1$UTC),origin="1970-01-01",tz="GMT")

2
You need to specify the format of you dateSotos
Read ?as.POSIXct and ?strptimeMichaelChirico

2 Answers

4
votes

This works for your example. See ?strptime for the format codes.

as.POSIXct("Fri Aug 10 04:42:47 +0000 2012",format="%a %b %d %H:%M:%S %z %Y",tz="GMT")

[1] "2012-08-10 04:42:47 GMT"
4
votes

You can also use parse_date_time from lubridate, which saves you the typing of spaces and % signs:

date_string = "Fri Aug 10 04:42:47 +0000 2012"

library(lubridate)

parse_date_time(date_string, "abdHMSzY", tz = "GMT")
# [1] "2012-08-10 04:42:47 GMT"