Date and Time Handling
Lesson 13 of 14 in Coddy's Data Manipulation in R course.
The language provides built-in functions and classes for working with date-time objects efficiently.
Date and Time Classes in R
R has three main classes for working with dates and times:
Date: Represents dates without timesPOSIXct: Represents date-times as the number of seconds since January 1, 1970POSIXlt: Represents date-times as a list of components (year, month, day, etc.)
Creating Date-Time Objects
You can create date-time objects using the following functions:
# Create a Date object
today <- Sys.Date()
# Create a POSIXct object
now <- Sys.time()
# Convert a string to a Date
date_from_string <- as.Date("2023-06-15")
# Convert a string to POSIXct
datetime_from_string <- as.POSIXct("2023-06-15 14:30:00")Formatting Date-Time Objects
Use format() to convert date-time objects to strings:
date <- as.Date("2023-06-15")
formatted_date <- format(date, "%B %d, %Y") # Returns: "June 15, 2023"Parsing Date-Time Strings
To parse date-time strings, use as.Date() or as.POSIXct() with a format string:
date_string <- "15/06/2023"
parsed_date <- as.Date(date_string, format = "%d/%m/%Y")Date-Time Calculations
R allows arithmetic operations on date-time objects:
today <- Sys.Date()
next_week <- today + 7 # Add 7 days
time_diff <- as.numeric(next_week - today) # Get difference in daysExtracting Components
You can extract specific components from date-time objects:
date <- as.Date("2023-06-15")
year <- format(date, "%Y")
month <- format(date, "%m")
day <- format(date, "%d")
hour <- format(date, "%H")
minute <- format(date, "%M")
second <- format(date, "%S")This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
MediumCreate a function that processes a list of events with their dates and times. The function should perform the following operations:
- Convert the input string into a data frame
- Parse the 'datetime' column into POSIXct objects
- Extract the day of the week for each event
- use the
weekdays()function. For example:weekdays(date)
- use the
- Calculate the duration in hours between each event and the first event
To get the first date time use:
mutate( datetime = as.POSIXct(datetime, format = "%Y-%m-%d %H:%M:%S"), first_date = min(datetime), ... )
- Format the 'datetime' column to display only the date in "YYYY-MM-DD" format
- Create a new column
time_categorybased on the hour of the event:- If hour is between 5 and 11 (inclusive), set to "Morning"
- If hour is between 12 and 16 (inclusive), set to "Afternoon"
- If hour is between 17 and 20 (inclusive), set to "Evening"
- Otherwise, set to "Night"
- Sort the data frame by the original datetime
- Print the resulting data frame only with the following columns (in this order):
event, datetime, day_of_week, duration_hours, date, time_category
Try it yourself
# Read input
con <- file("stdin", "r")
input_data <- suppressWarnings(readLines(con))
# Convert input string to data frame
events_df <- read.csv(text = input_data, stringsAsFactors = FALSE)
# TODO: Write your code below to process the events data frame
# 1. Parse the 'datetime' column into POSIXct objects
# 2. Extract the day of the week for each event
# 3. Calculate the duration in hours between each event and the first event
# 4. Format the 'datetime' column to display only the date in "YYYY-MM-DD" format
# 5. Create a new column 'time_category' based on the hour of the event
# 6. Sort the data frame by the original datetime
# Print the resulting data frame
print(events_df)