R lubridate: How To Efficiently Work With Dates and Times in R

Reading time:
time
min
By:
Dario Radečić
November 16, 2023

Data analytics and programming don't often have a lot of things in common. But where they're almost indistinguishable is the topic of dates. The skill of working with datetimes is an integral part of both areas and is something you'll want to master sooner rather than later. Newcomers often find this area challenging due to the sheer amount of options available, but the truth is that you'll only need 5% of the functionality on a daily basis, and the rest you can quickly find online. Today, we'll show you this 5% through a set of 15 useful examples with R lubridate. But first, <b>what is R lubridate, and what makes it better than the competition?</b> Let's answer that next. <blockquote>Functional programming in R? <a href="https://appsilon.com/functional-programming-in-r-part-1/" target="_blank" rel="noopener">Here's everything you need to know</a>.</blockquote> <h3>Table of contents:</h3><ul><li><strong><a href="#why">Why R Lubridate?</a></strong></li><li><strong><a href="#examples">15 Examples to Master R Lubridate</a></strong></li><li><a href="#summary"><strong>Summing up R Lubridate</strong></a></li></ul> <hr /> <h2 id="why">Why R Lubridate?</h2> You can think of R <code><a href="https://lubridate.tidyverse.org/" target="_blank" rel="noopener noreferrer">lubridate</a></code> as a comprehensive R package specifically designed to simplify the working process with dates and times. It's part of <a href="https://www.tidyverse.org/" target="_blank" rel="noopener noreferrer">tidyverse</a>, so it aligns nicely with the philosophy of clear and expressive coding. The package brings to the table a set of intuitive functions that make it easy for developers and data professionals to perform common tasks such as parsing dates, performing date arithmetic, and handling time zones. One of the main reasons you want to consider <b>using lubridate over the other datetime packages in R</b> is its user-friendly and intuitive syntax. Traditional R functions are often verbose and complex, and lubridate is here to simplify things. For this reason, lubridate is also appealing to beginners and those who care about code simplicity and maintainability. The rest of the article <b>assumes you have lubridate installed and loaded</b>. Use the following command to import it: <pre><code class="language-r">library(lubridate)</code></pre> Up next, we'll go over 15 concrete and useful examples so you can see why lubridate is so heavily used and loved by data professionals. <h2 id="examples">15 Examples to Master R Lubridate</h2> This section will get you started working with R lubridate. It doesn't matter if you're a newcomer to R and programming in general - the examples will be simple to follow and easy to understand. <h3>1. Get the Current Date and Time</h3> You can use the <code>now()</code> function in lubridate to get the current date and time based on your system's time zone. The function doesn't require any parameters. It is particularly useful when you need a timestamp for the exact moment when your script is running, such as logging events, timestamping transactions, or creating time-sensitive data entries: <pre><code class="language-r">current_time &lt;- now() current_time</code></pre> <img class="wp-image-21869 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0199720852b3d3e1316d9_image_2023-11-17_11-21-52.webp" alt="Getting the current date and time" width="500" height="123" /> Getting the current date and time <h3>2. Extract Date Components</h3> The <code>day()</code>, <code>month()</code>, and <code>year()</code> functions are handy for extracting the respective date components from date objects. Each function expects a date or datetime object as the input. These functions are great for breaking down a date into its constituent parts, which is useful for analysis, reporting, and data processing tasks where you need to categorize or compare data based on these individual components: <pre><code class="language-r">day(now()) month(now()) year(now())</code></pre> <img class="wp-image-21871 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019992a228de4b21abd64_image_2023-11-17_11-22-12.webp" alt="Extracting components from a date" width="492" height="216" /> Extracting components from a date <h3>3. Parse Date From Character Strings</h3> You can use the <code>ymd()</code>, <code>mdy()</code>, and <code>dmy()</code> functions to parse character strings into date objects. They expect the format to be year-month-day, month-day-year, and day-month-year, as the function name suggests. They are crucial for converting date strings from various sources into a standardized date format that R can understand and manipulate: <pre><code class="language-r">ymd("20231113") mdy("11/13/2023") dmy("13-11-2023")</code></pre> <img class="wp-image-21873 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0199a0b72d063b0673c29_image_2023-11-17_11-22-36.webp" alt="Parsing date from a character string" width="371" height="184" /> Parsing date from a character string <h3>4. Convert to Datetime From Other Formats</h3> The <code>as_datetime()</code> function is used to convert different date and time formats into POSIXct, a common datetime format in R. It accepts a wide range of inputs like character strings, numeric types, and factors. This function is invaluable for standardizing datetime information into a format suitable for analysis and keeping track of your data over time in general: <pre><code class="language-r">as_datetime("2023-11-13 17:34:51")</code></pre> <img class="wp-image-21875 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0199cabe86ac85914939f_image_2023-11-17_11-22-44.webp" alt="Converting string to datetime" width="590" height="58" /> Converting string to datetime <h3>5. Find the Difference Between Dates</h3> Subtracting two date objects in lubridate gives you the difference in time between them. This is a handy operation you'll do pretty often and it doesn't require a specific function - just subtract two dates the same way you would with numbers. You can use this technique in many areas like project planning, age calculation, and time series analysis: <pre><code class="language-r">start_date &lt;- ymd("20231101") end_date &lt;- ymd("20231113") time_difference &lt;- end_date - start_date time_difference</code></pre> <img class="wp-image-21877 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0199def34dd9b4d0f1f3a_image_2023-11-17_11-23-12.webp" alt="Finding difference between dates" width="577" height="64" /> Finding difference between dates <h3>6. Add or Subtract Time Units</h3> The <code>days()</code>, <code>months()</code> and <code>years()</code> functions can be used to create Period objects representing a specified number of days, months, or years. These can be added to or subtracted from date objects. A practical application of these functions would be calculating future dates (e.g., deadlines or anniversaries) or past dates (e.g., historical analysis): <pre><code class="language-r">future_date &lt;- now() + days(5) future_date <br>past_date &lt;- now() - months(3) past_date</code></pre> <img class="wp-image-21879 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0199f2c0cf4fd2c93c418_image_2023-11-17_11-25-18.webp" alt="Adding and subtracting from dates" width="537" height="183" /> Adding and subtracting from dates <h3>7. Compare Dates</h3> Date objects in R can be compared using standard comparison operators like <code>&lt;</code> or <code>&gt;</code>. This doesn't require a specific lubridate function - just compare the dates exactly the same as you would numbers. Date comparison is essential for sorting, filtering, or conditional operations based on dates: <pre><code class="language-r">ymd("20231101") &lt; ymd("20231029") ymd("20231101") &gt; ymd("20231029")</code></pre> <img class="wp-image-21881 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019a0c39a0a5ff7b9a1f9_image_2023-11-17_11-25-24.webp" alt="Comparing dates" width="544" height="124" /> Comparing dates <h3>8. Round Dates to the Nearest Unit</h3> The <code>round_date()</code> function, as the name suggests, rounds a date to the specified time unit, such as "month" or "year". This function is useful when you need to normalize dates for comparison or aggregation, like summarizing data on a monthly or yearly basis: <pre><code class="language-r">round_date(now(), "month")</code></pre> <img class="wp-image-21883 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019a220852b3d3e131f6a_image_2023-11-17_11-25-30.webp" alt="Rounding dates" width="417" height="65" /> Rounding dates <h3>9. Working with Time Zones</h3> You can use the <code>with_tz()</code> function to change the time zone of a datetime object without changing the actual time. It expects a datetime object and a string representing the time zone. This function is crucial for handling data collected across different time zones, and ensures consistent and accurate time representations: <pre><code class="language-r">with_tz(now(), tzone = "UTC") with_tz(now(), tzone = "EST")</code></pre> <img class="wp-image-21885 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019a393c80263c78303ac_image_2023-11-17_11-25-36.webp" alt="Working with time zones" width="490" height="124" /> Working with time zones <h3>10. Calculate Age from a Birthdate</h3> If you want a practical use case of different lubridate functions, look no more. You can combine the <code>interval()</code> and <code>years(1)</code> to calculate the age from a birthdate by creating a time interval and dividing it by one year. These calculations are widespread in demographics, marketing, and other fields where age is a significant factor, especially when represented as a floating point number: <pre><code class="language-r">birthdate &lt;- ymd("1985-12-15") age &lt;- interval(birthdate, now()) / years(1) age</code></pre> <img class="wp-image-21887 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019a5e64b1cc59a118e75_image_2023-11-17_11-25-44.webp" alt="Calculating age as a decimal number" width="629" height="122" /> Calculating age as a decimal number <h3>11. Format Date Output</h3> The <code>format()</code> function in R isn't specific to lubridate, but allows you to format date or POSIXct objects into character strings in different formats. This function is highly useful for preparing date-time data for reports, presentations, or exporting to other systems: <pre><code class="language-r">format(now(), "%A, %d %B %Y")</code></pre> <img class="wp-image-21889 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019a6bd9dcac7c574538d_image_2023-11-17_11-25-51.webp" alt="Custom formatted date output" width="502" height="66" /> Custom formatted date output <h3>12. Create a Date Sequence</h3> The <code>seq()</code> function, when used with date objects, generates a sequence of dates. The function requires start and end dates and a step size (e.g., "days"). Think of this last parameter as an interval. This function is useful for creating time series data, finding missing dates in your time series, and so on: <pre><code class="language-r">seq(ymd("20231001"), ymd("20231031"), by = "days")</code></pre> <img class="wp-image-21891 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019a70e8b4a4d7930e32b_image_2023-11-17_11-25-56.webp" alt="Creating a sequence between two dates" width="748" height="276" /> Creating a sequence between two dates <h3>13. Handle Leap Years</h3> You can use the <code>leap_year()</code> function to check whether a year is a leap year or not. It's nothing you can't implement on your own with the modulus operator, but this function is still the more convenient way to get the same functionality. This function is critical in calendar calculations, especially in applications that require precise date calculations, like age calculation or scheduling: <pre><code class="language-r">leap_year(2023) leap_year(2024)</code></pre> <img class="wp-image-21893 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019a88cff4e0613421fd0_image_2023-11-17_11-26-01.webp" alt="Checking for leap years" width="365" height="123" /> Checking for leap years <h3>14. Work With Durations and Periods</h3> The <code>duration()</code> and <code>period()</code> functions are used to create Duration and Period objects representing time spans. The first one represents exact time spans, while the second one respects calendar conventions. These functions are useful for precise time calculations and for handling regular time spans in scheduling: <pre><code class="language-r">duration(60, "seconds") period(2, "hours")</code></pre> <img class="wp-image-21895 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019aa588d6f7ecdfcb5b4_image_2023-11-17_11-26-10.webp" alt="Durations and periods" width="410" height="117" /> Durations and periods <h3>15. Extract Weekdays</h3> The <code>wday()</code> function is used to extract a weekday from a given date object, either as an index integer or as a factor. Setting the optional <code>label</code> parameter to <code>TRUE</code> will give you the actual day name. It's more or less a convenience function used when you want to aggregate or analyze data based on the day of the week: <pre><code class="language-r">wday(now()) wday(now(), label = TRUE)</code></pre> <img class="wp-image-21897 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b019ab93c80263c783097e_image_2023-11-17_11-26-17.webp" alt="Extracting weekdays and numbers" width="630" height="157" /> Extracting weekdays and numbers <hr /> <h2 id="summary">Summing up R Lubridate</h2> And there you have it - a brain-friendly introduction to working with dates and times with R lubridate. We think these 15 examples will be enough for most of the date-related things you'll want to do. Anything more complex will typically boil down to combining a couple of functions shown today. <i>What do you think of R lubridate? Is it the package you use daily to handle date and time manipulations? If so, what's your most commonly used function?</i> Make sure to let us know in the comment section below. <blockquote>Coming to R from Excel? <a href="https://appsilon.com/excel-functions-in-r/" target="_blank" rel="noopener">Here's a couple of advanced Excel-like functions in R for effective data manipulation</a>.</blockquote>

Have questions or insights?

Engage with experts, share ideas and take your data journey to the next level!

Is Your Software GxP Compliant?

Download a checklist designed for clinical managers in data departments to make sure that software meets requirements for FDA and EMA submissions.
Explore Possibilities

Share Your Data Goals with Us

From advanced analytics to platform development and pharma consulting, we craft solutions tailored to your needs.

Talk to our Experts
r
tutorials