Import the package. We will also make heavy usage of chaining: see magrittr’s documentation.
library(strptimer)
library(magrittr)
Let’s see what kind of componenets we can use in our time format.
time_bases()
code | base |
---|---|
p | am_pm |
C | century |
F | date |
c | datetime |
d | day |
w | day_of_week |
j | day_of_year |
H | hour |
M | minute |
m | month |
n | newline |
% | percent |
S | second |
t | tab |
R | time |
s | timestamp |
z | timezone |
V | week_of_year |
Y | year |
Each of these base time components can be used in a time format:
time_format(year, month, day)
## [1] "%Y%m%d"
Each base component can be modified in special ways. Let’s say we are curious about the time options for modifying month:
"month" %>% base_options
code | base | name | short | roman |
---|---|---|---|---|
b | month | 1 | 1 | |
B | month | 1 | ||
0m | month | 1 | ||
m | month |
The default value will have all always have all no options select. Each option has a corresponding function, which can assign that option. Each such function takes only one argument, except for digits (see example below).
time_format(month %>% short %>% name)
## [1] "%b"
For the most part, time options should be self explanatory. For more information, codes can be looked up in the ?strptime
documentation. Note that many time formats are possible to build but do not have corresponding codes.
time_format(month %>% short %>% roman)
## Error in function_list[[k]](value):
## base short roman
## ------ ------ ------
## month 1 1
##
## has no corresponding code
Let’s build a complicated date format just for fun:
time_format(year %>% short %>% religious,
"/",
month %>% name %>% short,
"/",
day %>% roman,
tab,
hour %>% twelve %>% roman,
":",
minute %>% roman,
":",
second %>% digits(3),
" ",
am_pm,
" ",
timezone %>% name)
## [1] "%Ey/%b/%0d%t%0I:%0M:%0S3 %p %Z"