-Dealing with Dates

#Getting current date & time

Sys.timezone()
[1] "Europe/Berlin"
> Sys.Date()
[1] "2018-09-07"
> Sys.time()
[1] "2018-09-07 12:58:09 CEST"

If using the lubridate package:

library(lubridate)
now()

#Converting strings to dates

Convert Strings to Dates:

x <- c("2015-07-01", "2015-08-01", "2015-09-01")

as.Date(x)
## [1] "2015-07-01" "2015-08-01" "2015-09-01"
circle-info

Note that the default date format is YYYY-MM-DD

use?strftimein your console to know the date format

Using the lubridate package:

lubridate package recogniced the common separators used when recording dates (“-“, “/”, “.”, and “”).

Create Dates by Merging Data:

#Extract & manipulate parts of dates

Manipulating data with lubridate

Change the values of date elements

#Creating date sequences

Using the lubridate package.

Creating sequences with time is very similar; however, we need to make sure our date object is POSIXct rather than just a Date object (as produced by as.Date):

#Calculations with dates

R stores date and time objects as numbers. But we can calculated it such as logical comparisons, addition, subtraction, and working with durations.

With the lubridate package

#Dealing with time zones & daylight savings

Change the time zone for a date/time with the with_tz() function.

Change the time zone without changing the clock time with force_tz().

Savings times to eliminate impacts on date/time calculations.

#Additional resources

Last updated