Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get number of days, months and weeks since Epoch in R

Tags:

r

epoch

What is the best way to get the number of days, months and weeks since Epoch time in R ?

( A solution exists for Java : Get the number of days, weeks, and months, since Epoch in Java )

I know to get seconds from epoch, but how to get number of weeks ?

as.integer( Sys.time())   #.... gives number of seconds since epoch time
like image 244
Soumya Boral Avatar asked Nov 25 '25 12:11

Soumya Boral


2 Answers

One option is to use lubridate::interval as:

library(lubridate)


span <- interval(ymd_hms("1970-01-01 00:00:00"), Sys.time())

as.period(span, unit = "days")
#[1] "17622d 19H 57M 10.5912010669708S"

as.period(span, unit = "months")
#[1] "579m 0d 19H 57M 10.5912010669708S"


as.period(span, unit = "years")
#[1] "48y 3m 0d 19H 57M 10.5912010669708S"
like image 138
MKR Avatar answered Nov 28 '25 02:11

MKR


The internal representation of "Date" class is the number of days since the Epoch. (If you have a POSIXct variable then convert it to Date class using as.Date first however watch out for time zone conversion problems.)

now <- Sys.Date() # Date
d <- as.numeric(now) # days since Epoch

Now use the facts that there are an average of 365.25 days per year and 365.25 / 12 days per month to get the years and months since the Epoch.

m <- d / (365.25 / 12) # months since Epoch
y <- d / 365.25 # years since Epoch

years/months/days

If we did not want years, months and days separately but rather want the number of whole years and months (0-11) and days (0-30) then use POSIXlt:

lt <- as.POSIXlt(format(Sys.Date()))
with(lt, data.frame(years = year - 70, months = mon - 0, days = mday - 1))

This also works if lt is a vector, e.g. lt <- c(lt, lt) .

like image 42
G. Grothendieck Avatar answered Nov 28 '25 02:11

G. Grothendieck



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!