12

I have the following data frame

> head(try)
     creates       time
1  128.29508 1417392072
3  236.98361 1417392072
7   98.45902 1417392072
9  157.44068 1417392131
10 227.38333 1417392131
11 242.03390 1417392131

> str(try)
'data.frame':   102968 obs. of  2 variables:
 $ creates: num  128.3 237 98.5 157.4 227.4 ...
 $ time   : Factor w/ 26418 levels "1417392071","1417392072",..: 2 2 2 3 3 3 3 3 5 5 ...

I am unable to convert the UNIX timestamp into datetime using the following methods I tried

> head(as.POSIXlt(as.numeric(try$time),origin="1970-01-01",tz="GMT"))
[1] "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:03 UTC" "1970-01-01 00:00:03 UTC"
[6] "1970-01-01 00:00:03 UTC"

> head(as.POSIXct(as.character(try$time),tz="GMT"))

Error in as.POSIXlt.character(x, tz, ...) : character string is not in a standard unambiguous format

> head(as.POSIXlt(as.POSIXct(as.vector(as.numeric(try$time)),origin="1970-01-01")))
[1] "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:02 UTC" "1970-01-01 00:00:03 UTC" "1970-01-01 00:00:03 UTC"
[6] "1970-01-01 00:00:03 UTC"

I'm not sure what I'm doing incorrectly here.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user3006691
  • 435
  • 3
  • 7
  • 16
  • For a solution based on **lubridate** [CRAN](https://CRAN.R-project.org/package=lubridate) package, see https://stackoverflow.com/questions/13998206/r-lubridate-converting-seconds-to-date `lubridate::as_datetime(try$time)` – josep maria porrà Sep 17 '21 at 21:46

4 Answers4

14

You have to convert from Factor to Character To Number before using as.POSIXct. The function is expecting an integer as a Unixtime

head(as.POSIXct(as.numeric(as.character(try$time)), origin="1970-01-01", tz="GMT"))
Emer
  • 3,734
  • 2
  • 33
  • 47
  • I'd tried that too and ended up with an error; > head(as.POSIXct(as.character(try$time),origin="1970-01-01",tz="GMT")) Error in as.POSIXlt.character(x, tz, ...) : character string is not in a standard unambiguous format – user3006691 Dec 10 '14 at 18:30
2

It's because the epoch is not numeric, try converting it into a number and it works like wonder!

try$time <- as.POSIXct(as.numeric(try$time), origin = '1970-01-01', tz = 'GMT')
989
  • 12,579
  • 5
  • 31
  • 53
Kushal Shah
  • 165
  • 1
  • 13
1

Try

head(as.POSIXct(as.integer(as.numeric(as.character(try$time)) / 1000.0), 
origin='1970-01-01', tz="GMT"))
0

What about

library("anytime")
anytime(try$time)

you can also get the date from the timestamps anydate(try$time)

and if you want UTC, you can do anytime(try$time, asUTC = TRUE)

temp
  • 82
  • 1
  • 10