5

I have a date that I convert to a numeric value and want to convert back to a date afterwards.

Converting date to numeric:

date1 = as.POSIXct('2017-12-30 15:00:00')
date1_num = as.numeric(date1)
# 1514646000

Reconverting numeric to date:

as.Date(date1_num, origin = '1/1/1970')
# "4146960-12-12"

What am I missing with the reconversion? I'd expect the last command to return my original date1.

ben_aaron
  • 1,504
  • 2
  • 19
  • 39

4 Answers4

4

As the numeric vector is created from an object with time component, reconversion can also be in the same way i.e. first to POSIXct and then wrap with as.Date

as.Date(as.POSIXct(date1_num, origin = '1970-01-01'))
#[1] "2017-12-30"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Excellent, and how would I reconstruct the time of the original `date1` "15:00:00"? – ben_aaron Sep 12 '19 at 16:18
  • @ben_aaron Just remove the `as.Date` wrapping `as.POSIXct(date1_num, origin = '1970-01-01')# [1] "2017-12-30 15:00:00 EST"` – akrun Sep 12 '19 at 16:19
3

You could use anytime() and anydate() from the anytime package:

R> pt <- anytime("2017-12-30 15:00:00")
R> pt
[1] "2017-12-30 15:00:00 CST"
R>
R> anydate(pt)
[1] "2017-12-30"
R>
R> as.numeric(pt)
[1] 1514667600
R>
R> anydate(as.numeric(pt))
[1] "2017-12-30"
R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
2

POSIXct counts the number of seconds since the Unix Epoch, while Date counts the number of days. So you can recover the date by dividing by (60*60*24) (let's ignore leap seconds), or convert back to POSIXct instead.

as.Date(as.numeric(date1)/(60*60*24), origin="1970-01-01")
[1] "2017-12-30"

as.POSIXct(as.numeric(date1),origin="1970-01-01")
[1] "2017-12-30 15:00:00 GMT"
James
  • 65,548
  • 14
  • 155
  • 193
1

Using lubridate :

lubridate::as_datetime(1514646000)
[1] "2017-12-30 15:00:00 UTC"
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167