R-bloggers

R-bloggers

R news and tutorials contributed by hundreds of R bloggers

A Comprehensive Introduction to Handling Date & Time in R

Posted on April 16, 2020 by Rsquared Academy Blog in R bloggers | 0 Comments

[This article was first published on Rsquared Academy Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here) Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In this tutorial, we will learn to handle date & time in R. We will start off by learning how to get current date & time before moving on to understand how R handles date/time internally and the different classes such as Date & POSIXct/lt . We will spend some time exploring time zones, daylight savings and ISO 8001 standard for representing date/time. We will look at all the weird formats in which date/time come in real world and learn to parse them using conversion specifications. After this, we will also learn how to handle date/time columns while reading external data into R. We will learn to extract and update different date/time components such as year, month, day, hour, minute etc., create sequence of dates in different ways and explore intervals, durations and period. We will end the tutorial by learning how to round/rollback dates. Throughout the tutorial, we will also work through a case study to better understand the concepts we learn. Happy learning!

Table of Contents

Resources

Below are the links to all the resources related to this tutorial:

new courses ad

Introduction

Date

Let us begin by looking at the current date and time. Sys.Date() and today() will return the current date.

Sys.Date() ## [1] "2020-04-17" lubridate::today() ## [1] "2020-04-17"

Time

Sys.time() and now() return the date, time and the timezone. In now() , we can specify the timezone using the tzone argument.

Sys.time() ## [1] "2020-04-17 17:37:21 IST" lubridate::now() ## [1] "2020-04-17 17:37:21 IST" lubridate::now(tzone = "UTC") ## [1] "2020-04-17 12:07:21 UTC"

AM or PM?

am() and pm() allow us to check whether date/time occur in the AM or PM ? They return a logical value i.e. TRUE or FALSE

lubridate::am(now()) ## [1] FALSE lubridate::pm(now()) ## [1] TRUE

Leap Year

We can also check if the current year is a leap year using leap_year() .

Sys.Date() ## [1] "2020-04-17" lubridate::leap_year(Sys.Date()) ## [1] TRUE

Summary

Function Description
Sys.Date() Current Date
lubridate::today() Current Date
Sys.time() Current Time
lubridate::now() Current Time
lubridate::am() Whether time occurs in am?
lubridate::pm() Whether time occurs in pm?
lubridate::leap_year() Check if the year is a leap year?

Your Turn