MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Setup
  • 1A: Fundamental Building Blocks
  • 1B: Compound Statements
  • 2: Ordered Collection
  • 3: Key-Value Map and Structures
  • 4: More Data types
  • 5: Iteration Constructs
  • 6: Other constructs
  • 7. Regex
  • 8. Date and Time
  • Revision
  • Practice Exercise

Date and Time Functions

Why Learn Date and Time Functions in Data Analytics?

Imagine you are studying customer churn for a subscription-based product. You receive a customer record showing:

  • Signup Date: "2026-01-15"
  • Cancellation Date: "2026-03-05"

You need to calculate exactly how many days the customer remained subscribed to compute their Life-Time Value (LTV). If you leave these values as raw text strings, you cannot subtract them! Trying to calculate "2026-03-05" - "2026-01-15" will result in an error.

To perform date calculations, filter logs by hour, or group data by month, you must convert text strings into official Date or Datetime objects in R.


1. R's Date and Datetime Classes

R has two primary built-in classes for dates and times:

  • Date: Represents a calendar date (Year-Month-Day).
  • POSIXct: Represents a specific date and time, stored internally as the number of seconds since January 1, 1970 (ideal for data frames).
# Get current date and time
today <- Sys.Date()
right_now <- Sys.time()

print(today)     # "2026-06-20"
print(right_now) # "2026-06-20 09:54:12 EDT"

2. Parsing Strings to Dates: as.Date() and as.POSIXct()

To convert string data into actual date/datetime objects, use as.Date() or as.POSIXct() and specify the formatting pattern:

Formatting Code Meaning Example
%Y 4-digit year 2026
%y 2-digit year 26
%m Month (01-12) 03
%d Day of the month (01-31) 15
%H Hour (24-hour format) 14
%M Minute 30
%S Second 45
# Parsing a standard date string
d1 <- as.Date("15/01/2026", format = "%d/%m/%Y")
print(d1) # "2026-01-15"

# Parsing a datetime string (POSIXct)
dt1 <- as.POSIXct("2026-01-15 14:30:00", format = "%Y-%m-%d %H:%M:%S")
print(dt1)

3. Formatting Date Objects to Strings: format()

To format a date object back into a custom string display (equivalent to Python's strftime):

today <- Sys.Date()
formatted_today <- format(today, "%B %d, %Y")
print(formatted_today) # "June 20, 2026"

4. Date and Time Calculations

You can add or subtract numbers directly from Date objects (R treats the number as days). For POSIXct datetime objects, R treats the number as seconds.

To calculate the exact difference between two dates using custom units (days, hours, weeks), use difftime():

start_date <- as.Date("2026-01-15")
end_date <- as.Date("2026-03-05")

# Simple subtraction returns days
time_span <- end_date - start_date
print(time_span) # Time difference of 49 days

# Using difftime for custom units
weeks_diff <- difftime(end_date, start_date, units = "weeks")
print(weeks_diff) # Time difference of 7 weeks

5. The lubridate Package

While R's base date tools are decent, the R community heavily uses the lubridate package (part of Tidyverse) which simplifies parsing dates without needing formatting strings:

library(lubridate)

# Parses automatically!
d1 <- ymd("2026-01-15")
d2 <- dmy("15-Jan-2026")

print(d1 == d2) # TRUE

1. Flexible Parsing: parse_date_time()

If you have columns containing dates formatted in different ways (e.g. some are "2026-01-15" and others are "15/01/2026"), the parse_date_time(x, orders) function lets you supply a list of possible format order variations to parse them successfully:

mixed_dates <- c("2026-01-15", "15/01/2026", "Jan 15, 2026")
# Supply possible orders: year-month-day, day-month-year, month-day-year
parsed <- parse_date_time(mixed_dates, orders = c("ymd", "dmy", "mdy"))
print(parsed)

2. Creating Dates from Columns: make_date() and make_datetime()

If your dataset separates year, month, and day into individual columns (common in flight or weather logs), combine them into single date objects using make_date() or make_datetime():

years <- c(2025, 2026)
months <- c(12, 1)
days <- c(25, 15)

dates <- make_date(year = years, month = months, day = days)
print(dates) # "2025-12-25" "2026-01-15"

3. Extracting Date/Time Components

To extract specific sub-units from a date or datetime object:

  • year() / month() / day(): Extract year, month number, day number.
  • mday() / yday(): Day of the month (1-31), day of the year (1-366).
  • wday(..., label = TRUE): Day of the week (returns factor like "Mon", "Tue").
  • hour() / minute() / second(): Extract time components.
my_date <- ymd_hms("2026-06-20 15:30:45")
print(year(my_date))          # 2026
print(month(my_date))         # 6
print(wday(my_date, label = TRUE)) # Sat

4. Time Spans: Durations vs. Periods

lubridate differentiates between physical durations (elapsed seconds) and human periods (calendar adjustments like leap years and daylight savings):

  • Durations: Represent exact elapsed seconds. Created using the prefix d (e.g., ddays(1) is exactly 86400 seconds).
  • Periods: Represent human clock/calendar units. Created without the d prefix (e.g., days(1) represents "one calendar day", adjusting for leap days and DST offsets).
# Duration: always 86400 seconds
print(ddays(1)) # "86400s (~1 days)"

# Period: 1 calendar day
print(days(1))  # "1d"

# Leap year calculation difference
leap_day <- ymd("2024-02-28")

print(leap_day + dyears(1)) # "2025-02-27" (adding exactly 365 days of seconds)
print(leap_day + years(1))  # "2025-02-28" (adding exactly 1 calendar year)

Hands-on Exercises

Exercise 1: Subscription Length Calculation

A user signed up on "03-Mar-2026" and cancelled their account on "28-Apr-2026". Write R code to:

  1. Parse both dates into Date variables. (Hint: "03-Mar-2026" uses %b for abbreviated month name, i.e., %d-%b-%Y).
  2. Calculate the difference in days using simple subtraction.
  3. Calculate the difference in weeks using difftime().
  4. Print both calculations.
# Write your code below and click Run Code
Click to view Answer
signup <- as.Date("03-Mar-2026", format = "%d-%b-%Y")
cancel <- as.Date("28-Apr-2026", format = "%d-%b-%Y")

days_active <- cancel - signup
weeks_active <- difftime(cancel, signup, units = "weeks")

print(days_active)  # Time difference of 56 days
print(weeks_active) # Time difference of 8 weeks

Exercise 2: Future Target Shift

A project deadline is set for 45 days after today's date. Write R code to:

  1. Get the current date using Sys.Date().
  2. Add 45 to today's date using a vectorized addition operation to calculate the future deadline date.
  3. Format the future date as "DD/MM/YYYY" and print it.
# Write your code below and click Run Code
Click to view Answer
today <- Sys.Date()
deadline <- today + 45
formatted_deadline <- format(deadline, "%d/%m/%Y")

print(formatted_deadline)
Privacy Policy | Terms & Conditions