Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a character timestamp into a date-time object in R

Tags:

datetime

r

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

like image 921
Lesnar Avatar asked Dec 04 '25 18:12

Lesnar


2 Answers

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"
like image 151
Andrew Gustar Avatar answered Dec 06 '25 06:12

Andrew Gustar


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"
like image 27
acylam Avatar answered Dec 06 '25 06:12

acylam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!