Dates and Time

There are three types of data that refer to an instant in time:

  • A date (“2016-08-16”)
  • A time within a day (“19:11:59 UTC”)
  • And a date-time. This is a date plus a time (“2023-10-31 18:15:48 UTC”)

Creating Date and Time Formats

There are 3 ways for converting to Date and Time

 

  1. From an individual Date
  2. Converting Date and Time from a string
  3. From an Existing Date/ time

Converting Date and Time from a String

Date and time is usually presented as a string. To convert strings into dates and date-times, you can utilize the convenient tools offered by the lubridate package in R. This tool will automatically decipher the the date and time format.

For example, for the date 2023-20-23, you would use the order ymd

ymd(2023-20-23)

Adding Time to a Date

The functions like ymd() are used for generating dates. If you want to create a date-time instead, you can do so by appending an underscore followed by one or more of the letters "h," "m," and "s" to the name of the parsing function.

Example 1 : January 21, 2012 at 5:30 AM and 59 secs
mdy_hms("January 21, 2012 05:30:59")

> mdy_hms("January 21, 2012 05:30:59")
[1] "2012-01-21 05:30:59 UTC"

Example 2: Monday, 30 october, 2023

dmy("Monday, 30 october, 2023")
[1] "2023-10-30"

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top