Learn R · 12/15

Working with Dates and Times (lubridate)

6 min read

Working with Dates and Times (lubridate)

Welcome, intrepid data wrangler! 🤠 You've wrestled with numbers, tamed text, and now you face one of the most notoriously slippery beasts in the data jungle: dates and times. Without the right tools, handling them can feel like trying to catch smoke with your bare hands. You might find yourself in a bizarre world where "01-02-2023" could be January 2nd or February 1st, and adding "one month" to a date is a riddle wrapped in an enigma.

This is where the lubridate package in R swoops in to save the day! 🦸‍♀️ It provides a consistent and easy-to-remember set of tools to make working with dates and times not just manageable, but dare we say, enjoyable.

Getting Started: Installation

First things first, let's get lubridate installed and ready to go. Since it's part of the tidyverse, you might already have it. If not, open up your R console and type:

r
# To install the full tidyverse, which includes lubridate
install.packages("tidyverse")

# Or, to install only lubridate
install.packages("lubridate")

Once installed, you need to load it into your R session every time you want to use it:

r
library(lubridate)

Now, let's dive into the fun stuff!


1. Parsing Strings into Dates and POSIXct Objects

The Problem: Your data often comes with dates and times stored as plain text (character strings). To R, "2023-10-26" is just a sequence of characters, not a point in time. You can't perform any meaningful calculations or analysis on it until you convert it into a proper date or date-time format.

The lubridate Solution: lubridate offers a family of functions that make parsing strings into dates a breeze. The function names correspond to the order in which the year (y), month (m), and day (d) appear in your string.

Here are the most common ones:

  • ymd(): for dates like "2023-10-26"
  • mdy(): for dates like "October 26, 2023" or "10/26/2023"
  • dmy(): for dates like "26-Oct-2023" or "26/10/2023"

Example:

r
# Parsing a date in year-month-day format
ymd("2023-10-26")

# Parsing a date in month-day-year format
mdy("October 26, 2023")

# Parsing a date in day-month-year format
dmy("26-October-2023")

What about times? 🕰️

If your strings also include time information, you can simply append _hms (hour, minute, second), _hm, or _h to the date parsing functions.

Example:

r
# Parsing a date-time string
ymd_hms("2023-10-26 14:30:00")

When you parse a string with time information, lubridate creates a POSIXct object. Don't let the name intimidate you! Think of it as R's way of storing the exact number of seconds that have passed since the beginning of 1970. This allows for very precise date and time calculations.


2. Extracting Components: Year, Month, Day, and Hour

The Problem: Once you have your dates and times properly formatted, you'll often need to pull out specific pieces of information. For instance, you might want to analyze sales data by month, or website traffic by the hour of the day.

The lubridate Solution: lubridate provides a set of intuitive accessor functions to extract individual components from a date or date-time object.

  • year(): Extracts the year.
  • month(): Extracts the month. You can also get the month name.
  • day(): Extracts the day of the month.
  • hour(): Extracts the hour.
  • minute(): Extracts the minute.
  • second(): Extracts the second.
  • wday(): Extracts the day of the week.

Example:

r
# Create a date-time object
my_datetime <- ymd_hms("2024-07-04 10:30:15")

# Extract components
year(my_datetime)
# [1] 2024

month(my_datetime, label = TRUE)
# [1] Jul
# Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < Oct < Nov < Dec

day(my_datetime)
# [1] 4

hour(my_datetime)
# [1] 10

wday(my_datetime, label = TRUE)
# [1] Thu
# Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat

Fun Fact! 🎉 The first text message ever sent was on December 3rd, 1992. Let's see what day of the week that was:

r
first_sms <- ymd("1992-12-03")
wday(first_sms, label = TRUE, abbr = FALSE)
# [1] Thursday

So, the dawn of a new communication era happened on a Thursday!


3. Time Math: Working with Periods and Durations

The Problem: Adding and subtracting time can be tricky. Adding "one month" to January 31st should result in the last day of February, not March 2nd or 3rd. Similarly, a "day" isn't always 24 hours long due to daylight saving time.

The lubridate Solution: lubridate introduces two types of time spans to handle these situations: Periods and Durations.

  • Periods: Represent human-centric units of time like years, months, and days. They intelligently handle things like leap years and the varying number of days in a month. You create them with functions like years(), months(), and days().

  • Durations: Represent an exact number of seconds. A duration of one day is always 86,400 seconds. You create them with functions like dyears(), dmonths() (not recommended due to ambiguity), and ddays().

Real-Life Scenario: Subscription Renewal vs. A 24-Hour Sale

Imagine you're running a streaming service.

  • For a monthly subscription renewal: You'd use a Period. If a user signs up on January 31st, their next billing date should be February 28th (or 29th in a leap year).

    r
    start_date <- ymd("2024-01-31")
    renewal_date <- start_date + months(1)
    # renewal_date will be "2024-02-29"
  • For a 24-hour flash sale: You'd use a Duration. You want the sale to last exactly 24 hours from the moment it starts.

    r
    sale_start <- ymd_hms("2024-03-10 01:00:00") # Before a DST change
    sale_end <- sale_start + ddays(1)
    # sale_end will be "2024-03-11 02:00:00" if DST occurs

    Notice how adding a duration of one day might result in a different clock time if daylight saving time starts or ends.


4. Handling Time Zones Effectively

The Problem: Your data might come from different parts of the world, or you might need to display times in a specific time zone. Ignoring time zones is a recipe for confusion and errors, especially when coordinating across regions.

The lubridate Solution: lubridate provides straightforward functions for managing time zones. You can see a list of all available time zone names by running OlsonNames().

  • with_tz(): Changes how a time is displayed by converting it to a new time zone. The underlying moment in time remains the same.
  • force_tz(): Changes the time zone of a date-time object without changing the clock time. This results in a different moment in time.

Real-Life Scenario: Scheduling an International Meeting

Let's say you're in New York ("America/New_York") and need to schedule a meeting with a colleague in London ("Europe/London") for 9:00 AM your time.

r
# Create the meeting time in your time zone
meeting_nyc <- ymd_hm("2024-11-05 09:00", tz = "America/New_York")

# Find out what time that is for your colleague in London
meeting_london <- with_tz(meeting_nyc, "Europe/London")

# meeting_london will be "2024-11-05 14:00:00 GMT"

Now, imagine you received a meeting invitation for 2:00 PM, but the sender forgot to specify the time zone. You know it's a London-based company. You can use force_tz() to correctly assign the time zone.

r
# The ambiguous meeting time
ambiguous_time <- ymd_hm("2024-11-05 14:00") # This defaults to your system's time zone or UTC

# Forcing the correct time zone
correct_time <- force_tz(ambiguous_time, "Europe/London")

And there you have it! You're now equipped with the fundamental skills to wrangle dates and times in R with lubridate. Go forth and analyze your time-series data with confidence! 🚀


Further Reading and References

Challenge

Flash Sale Data Analysis

You are a data analyst for an e-commerce company that just concluded a 48-hour global flash sale. The sale started at 2024-02-28 10:00:00 local time in New York (America/New_York).

Your task is to process a vector of raw purchase timestamps, which are character strings recorded in America/New_York time, and derive key business insights. You must use the lubridate package for all date-time manipulations.

Your tasks:

  1. Ensure the lubridate library is loaded.
  2. Parse the launch_string and correctly assign it the "America/New_York" time zone. Store this in a variable named launch_time_nyc.
  3. Parse the purchase_strings vector into a proper date-time vector named purchase_times_nyc. Since these timestamps were recorded without time zone information, you must explicitly assign them the "America/New_York" time zone.
  4. The flash sale lasted for an exact 48-hour duration. Calculate the precise end time of the sale and store it in a variable named sale_end_time_nyc.
  5. For standardized reporting, convert the purchase_times_nyc vector to the "UTC" time zone. Store the result in purchase_times_utc.
  6. From the purchase_times_utc vector, extract the abbreviated name of the weekday for each purchase (e.g., "Mon", "Tue"). Store this character vector in purchase_weekdays.
  7. Determine if the final purchase recorded in purchase_times_nyc occurred before the sale_end_time_nyc. Store the result as a single logical value (TRUE or FALSE) in a variable named last_purchase_in_sale.

Expected result

After running your code, the following variables should be correctly populated in your environment:

  • launch_time_nyc: A POSIXct object representing 2024-02-28 10:00:00 with the America/New_York timezone.
  • purchase_times_nyc: A POSIXct vector corresponding to the purchase_strings, correctly parsed and assigned the America/New_York timezone.
  • sale_end_time_nyc: A POSIXct object representing 2024-03-01 10:00:00 in the America/New_York timezone.
  • purchase_times_utc: A POSIXct vector where each element is the UTC equivalent of the corresponding time in purchase_times_nyc. The first element should be 2024-02-28 15:05:31 UTC.
  • purchase_weekdays: A character vector with the values c("Wed", "Wed", "Thu", "Thu", "Fri").
  • last_purchase_in_sale: A logical variable with the value FALSE, as the last purchase was recorded one second after the sale officially ended.
r

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.