Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create date from datetime (using lubridate)?

Assume I have created a variable containing date and time:

a <- ymd_hms("2014-01-01 12:23:34")

How do I create another variable that only has the date? That is, what should I do to transform a's value to be identical to b's value where b is

b <- ymd("2014-01-01")
like image 493
paljenczy Avatar asked Feb 25 '15 20:02

paljenczy


People also ask

What does the Lubridate function do?

Description Functions to work with date-times and time-spans: fast and user friendly parsing of date-time data, extraction and updating of components of a date-time (years, months, days, hours, minutes, and seconds), algebraic manipulation on date-time and time-span objects.

What does Lubridate do in R?

Lubridate is an R package that makes it easier to work with dates and times.

How do I extract year from date in Lubridate?

Date("01/01/2009", format = "%m/%d/%Y"); lubridate::year(x) .

How do I convert a character to a date in R?

You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.


2 Answers

You can just use round_date

round_date(a, "day")
[1] "2014-01-02 UTC"

EDIT

You do need to be careful with rounding the time though. For complete equivalence here you would need to use floor_date.

identical(ymd("2014-01-01"), floor_date(a, "day"))
[1] TRUE
like image 162
cdeterman Avatar answered Oct 04 '22 14:10

cdeterman


Using date() is much shorter and avoids any issues with rounding.

library(lubridate)
date(a)
[1] "2014-01-01"
like image 38
Nakx Avatar answered Oct 04 '22 15:10

Nakx