Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R lubridate converting seconds to date

Tags:

r

lubridate

I have a simple question regarding R's lubridate package. I've a series of timestamps in seconds since epoch. I want to convert this to YYYY-MM-DD-HH format. In base R, I can do something like this to first convert it to a date format

> x = as.POSIXct(1356129107,origin = "1970-01-01",tz = "GMT") > x [1] "2012-12-21 22:31:47 GMT" 

Note the above just converts it to a date format, not the YYYY-MM-DD-HH format. How would I do this in lubridate? How would I do it using base R?

Thanks much in advance

like image 795
broccoli Avatar asked Dec 21 '12 22:12

broccoli


People also ask

How do I convert seconds to minutes in R?

First, you are converting the seconds into a Period (lubridate's object to represent time lapses) using seconds_to_period() function. The result of that looks like this "2H 23M 20S" Then, using hour() and minute() you can extract the units you need, in this case hours and minutes.

How do I change date format in R?

To format = , provide a character string (in quotes) that represents the current date format using the special “strptime” abbreviations below. For example, if your character dates are currently in the format “DD/MM/YYYY”, like “24/04/1968”, then you would use format = "%d/%m/%Y" to convert the values into dates.

What does Lubridate do in R?

Lubridate is an R package that makes it easier to work with dates and times. Below is a concise tour of some of the things lubridate can do for you. Lubridate was created by Garrett Grolemund and Hadley Wickham, and is now maintained by Vitalie Spinu.


2 Answers

lubridate has an as_datetime() that happens to have UNIX epoch time as the default origin time to make this really simple:

> as_datetime(1356129107) [1] "2012-12-21 22:31:47 UTC" 

more details can be found here: https://rdrr.io/cran/lubridate/man/as_date.html

like image 81
leerssej Avatar answered Sep 21 '22 23:09

leerssej


Dirk is correct. However, if you are intent on using lubridate functions:

paste( year(dt), month(dt), mday(dt), hour(dt) sep="-") 

If on the other hand you want to handle the POSIXct objects the way they were supposed to be used then this should satisfy:

format(x, format="%Y-%m-%d-%H") 
like image 39
IRTFM Avatar answered Sep 21 '22 23:09

IRTFM