Using lubridate to Work with Dates

Thursday, October 16

Today we will…

  • Reminder About Lab 3 / Challenge 3 Revisions
  • Reminder About Lab 4 Peer Code Review
  • Week 6 Layout
    • What to Expect
    • Midterm Portfolios
    • How to Get Started
  • New Material
    • Working with Date & Time Variables
  • PA 5.2: Jewel Heist

Lab 3 / Challenge 3 Revisions

Lab 3 / Challenge 3 Revisions

Revisions are due by Friday

Any problem receiving a “Growing” can be revised and submitted for additional feedback

Don’t forget to complete your Lab 4 code review!

Don’t forget to complete your Lab 4 code review!


Make sure your feedback follows the code review guidelines.

Insert your review into the comment box!

Week 6 Layout

Week 6 Layout

  • Tuesday: Version Control
    • Live Code / Troubleshoot In-Class
    • Midterm Portfolio Work Session
  • Thursday: Midterm Portfolio Work Session
    • Midterm Portfolios Due Sunday, October 19

What to Expect

You will create a Midterm Portfolio, with code covering the learning targets we have covered thus far in the course.

  • Your code will be pulled from your Lab and Challenge assignments.
  • You will write reflections on how you’ve:
    • revised your thinking
    • extended your thinking
    • supported and collaborated with your peers

Getting Started

  1. Follow these directions to install git and sign-up for a GitHub account
  2. Follow these directions to fork a copy of the Final Portfolio repository.
  3. Start finding excerpts of code you wrote for the Labs or Challenges that fit each learning target.
  4. Sign-up for a time to meet with Dr. T during Week 7

Date + Time Variables

Why are dates and times tricky?

When parsing dates and times, we have to consider complicating factors like…

  • Daylight Savings Time.
    • One day a year is 23 hours; one day a year is 25 hours.
    • Some places use it, some don’t.
  • Leap years – most years have 365 days, some have 366.
  • Time zones.

lubridate

  • Convert a date-like variable (“May 8, 1995”) to a date or date-time object.

  • Find the weekday, month, year, etc from a date-time object.

  • Convert between time zones.

The image shows the hex logo for the lubridate R package. The logo is a green hexagon with a stylized calendar in the center. The calendar has a small clock icon overlapping its bottom left corner, symbolizing time-related functions. The text 'lubridate' appears prominently below the calendar icon within the hexagon. Lubridate is commonly used in R for working with date and time data.

Note

The lubridate package installs and loads with the tidyverse.

Creating date-time Objects

From individual components:

make_date(year = 1995, month = 05, day = 08)
[1] "1995-05-08"

From a string:

mdy("August 29, 1991")
[1] "1991-08-29"

With a time zone:

dmy("29-August-1991", 
    tz = "America/Denver")
[1] "1991-08-29 MDT"
dmy_hms("29-August-1991 9:32:12", 
        tz = "America/Denver")
[1] "1991-08-29 09:32:12 MDT"

Common Mistake with Dates

as_datetime(2023-02-6)
[1] "1970-01-01 00:33:35 UTC"
my_date <- 2023-02-6
my_date
[1] 2015


What’s wrong here?


Make sure you use quotes!

  • 2,015 seconds \(\approx\) 33.5 minutes

Extracting date-time Components

bday <- ymd_hms("1989-01-14 12:03:12", 
                tz = "America/Denver")
bday
[1] "1989-01-14 12:03:12 MST"


year(bday)
[1] 1989
month(bday)
[1] 1
day(bday)
[1] 14
hour(bday)
[1] 12
wday(bday)
[1] 7
wday(bday, 
     label = TRUE, 
     abbr = FALSE)
[1] Saturday
7 Levels: Sunday < Monday < Tuesday < Wednesday < Thursday < ... < Saturday

Subtraction with date-time Objects

Doing subtraction gives you a difftime object.

difftime objects do not always have the same units – it depends on the scale of the objects you are working with.

How old am I?

today() - mdy(01141989)
Time difference of 13423 days


How long did it take me to type this slide?

begin <- mdy_hms("10/13/2025 6:40:34")
finish <- mdy_hms("10/13/2025 6:43:11")

finish - begin
Time difference of 2.616667 mins

Durations and Periods

Durations will always give the time span in an exact number of seconds.

as.duration(
  today() - mdy(01141989)
            )
[1] "1159747200s (~36.75 years)"

Periods will give the time span in more approximate, but human readable times.

as.period(
  today() - mdy(01141989)
  )
[1] "13423d 0H 0M 0S"

Durations and Periods

We can also add time to date-time objects:

  • days(), years(), etc. will add a period of time.
  • ddays(), dyears(), etc. will add a duration of time.

Because durations use the exact number of seconds to represent days and years, you might get unexpected results.


When is is my 99th birthday?

mdy(01141989) + years(99)
[1] "2088-01-14"
mdy(01141989) + dyears(99)
[1] "2088-01-14 18:00:00 UTC"

Intervals of Time

Suppose American Airlines requires members to travel within 4 weeks before or after their birthday to earn a “Birthday Bonus Flight.”

Well, we first need to make an interval of time around my birthday.

bonus_flight_window <- interval(
  bday - weeks(4),
  bday + weeks(4)
  )


Then I can check if today is within this interval.

today() %within% bonus_flight_window
[1] FALSE

Time Zones…

…are complicated!


Specify time zones in the form:

  • {continent}/{city} – “America/Denver”, “Africa/Nairobi”
  • {ocean}/{city} – “Pacific/Auckland”

What time zone does R think I’m in?

Sys.timezone()
[1] "America/Los_Angeles"

Time Zones

You can change the time zone of a date in two ways:

x <- ymd_hms("2025-10-13 18:00:00", 
             tz = "Europe/Copenhagen")

with_tz()

Keeps the instant in time the same, but modifies the representation based on the new time zone

x |> 
  with_tz(tzone = "America/Los_Angeles")
[1] "2025-10-13 09:00:00 PDT"
x |> 
  with_tz(tzone = "Asia/Kolkata")
[1] "2025-10-13 21:30:00 IST"

force_tz()

Changes the instant in time by forcing a time zone change.

x |> 
  force_tz(tzone = "America/Los_Angeles")
[1] "2025-10-13 18:00:00 PDT"
x |> 
  force_tz(tzone = "Asia/Kolkata")
[1] "2025-10-13 18:00:00 IST"

Common Mistake with Dates

When you read data in or create a new date-time object, the default time zone (if not specified) is UTC (Universal Time Coordinated)*.

*UTC is the same as GMT (Greenwich Mean Time)


So, make sure you specify your desired time zone!

x <- mdy("11/20/1993")
tz(x)
[1] "UTC"
x <- mdy("11/20/1993", 
         tz = "America/Los_Angeles")
tz(x)
[1] "America/Los_Angeles"

PA 5.2: Jewel Heist

The image displays five colorful gemstones placed on a dark surface. Each gem has a distinct color and shape. A rectangular green gem (emerald-like) on the left. A round white gem (resembling a diamond) at the top. An oval pink gem in the center. An oval blue gem in the foreground. An oval yellow gem in the background on the right. The gems are cut and polished, reflecting light and showing their intricate facets. They appear to represent a variety of precious stones with vibrant colors.

This activity will require knowledge of:

  • Converting time zones
  • Extracting components of a date
  • Filtering based on date components
  • Making intervals of time
  • Filtering values that fall into an interval
  • Finding the duration between two dates
  • Modulus division

None of us have all these abilities. Each of us has some of these abilities.

Pair Programming Expectations

A diagram shows a collaborative software development process in four stages arranged in a cycle. At the top, a woman speaks with the label 'VOCALIZE.' To the right, she points to a diagram with the label 'EXPLAIN.' At the bottom, a man types on a laptop with the label 'IMPLEMENT.' On the left, a computer monitor displays a bug symbol with the label 'DEBUG.' Arrows connect the stages in a loop: Vocalize → Explain → Implement → Debug → back to Vocalize.

External Resources

During the Practice Activity, you are not permitted to use Google or ChatGPT for help.


You are permitted to use:

  • today’s handout,
  • the lubridate cheatsheet,
  • the course slides, and
  • the course textbook

Submission

Submit the name of the thief to the Canvas Quiz.

  • Each person will input the full name of the thief into the PA 5.2 quiz.
  • The person who last occupied the role of Computer will submit the link to your group’s Colab notebook.
    • Please don’t forget to put your names at the top!

5-minute break

Team Assignments - 9am

The partner who has broken the most bones starts as the Talker!

Team Assignments - 12pm

The partner who has broken the most bones starts as the Talker!