Reconvert numeric date to POSIXct R
Asked Answered
Q

4

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.

Qualified answered 12/9, 2019 at 16:12 Comment(0)
K
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"
Kahle answered 12/9, 2019 at 16:13 Comment(2)
Excellent, and how would I reconstruct the time of the original date1 "15:00:00"?Qualified
@Qualified Just remove the as.Date wrapping as.POSIXct(date1_num, origin = '1970-01-01')# [1] "2017-12-30 15:00:00 EST"Kahle
G
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> 
Gaffe answered 12/9, 2019 at 16:19 Comment(0)
A
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"
Armorial answered 12/9, 2019 at 16:33 Comment(0)
L
1

Using lubridate :

lubridate::as_datetime(1514646000)
[1] "2017-12-30 15:00:00 UTC"
Loner answered 12/9, 2019 at 20:44 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.