-
Notifications
You must be signed in to change notification settings - Fork 0
Formatting dates
R provides a number of ways to format Date class (integer days since some start date) and POSIX class (real number of seconds since some start time) values into human-friendly time strings.
First we need some Date and POSIX objects to play with.
# make a Date object, and get the current date
dates <- c(as.Date("1995-12-28"), Sys.Date())
# make a POSIX object and get the curret date-time
datetimes <- c(as.POSIXct("1995-12-28 17:05:00"), Sys.time())Now use format() with a formatting pattern to lay the dates and times
out as you would like. Here’s a handy table showing different date
formats from here
| Symbol | Meaning | Example |
|---|---|---|
| %d | day as a number (0-31) | 01-31 |
| %a | abbreviated weekday | Mon |
| %A | unabbreviated weekday | Monday |
| %m | month (00-12) | 00-12 |
| %b | abbreviated month | Jan |
| %B | unabbreviated month | January |
| %y | 2-digit year | 07 |
| %Y | 4-digit year | 2007 |
So, format the date using combinations of the codes.
format(dates, "%B %d, %Y")## [1] "December 28, 1995" "March 27, 2021"
format(dates, "%Y/%m/%d")## [1] "1995/12/28" "2021/03/27"
And with date time you can add %H, %M, %S and %Z into the mix.
There’s a lot of other formats available, see ?strftime for examples.
You can add in leteral text, too.
format(datetimes, "%b %d, %Y @ %H:%M:%S")## [1] "Dec 28, 1995 @ 17:05:00" "Mar 27, 2021 @ 13:42:45"
format(datetimes, "the epoch will start on %Y-%m-%dT%H:%M:%S %Z or shortly thereafter")## [1] "the epoch will start on 1995-12-28T17:05:00 EST or shortly thereafter"
## [2] "the epoch will start on 2021-03-27T13:42:45 EDT or shortly thereafter"
The lubridate package
The lubridate makes working with date am time formatting (input and output) very easy. It’s part of the tidyverse Be sure to check out it’s tutorial page.
lubridate has many tools available, but one that is often helpful is
easy formatting into ISO_8601 format.
lubridate::format_ISO8601(datetimes)## [1] "1995-12-28T17:05:00" "2021-03-27T13:42:45"
Formatting for ggplot2
Formatting dates for ggplot2 axes is easy once you have a hang of the
formatting codes. So to format dates as e.g. October-01, you’d use
scale_x_date(date_labels='%B-%d'). There’s a nice detailed blog post
here