Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reconvert numeric date to POSIXct R

Tags:

r

posixct

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.

like image 493
ben_aaron Avatar asked Sep 12 '19 16:09

ben_aaron


2 Answers

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"
like image 123
akrun Avatar answered Oct 11 '22 07:10

akrun


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> 
like image 3
Dirk Eddelbuettel Avatar answered Oct 11 '22 05:10

Dirk Eddelbuettel