/
10-lubridate.Rmd
1814 lines (1370 loc) · 50.2 KB
/
10-lubridate.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Date & Time {#date-and-time-in-r}
## Introduction
```{r pkg_load, echo=FALSE, message=FALSE, warning=FALSE}
library(knitr)
library(kableExtra)
library(magrittr)
library(lubridate)
library(rversions)
library(readr)
library(dplyr)
```
Let us begin by looking at the current date and time.
### Date
`Sys.Date()` and `today()` will return the current date.
```{r sys_date}
Sys.Date()
lubridate::today()
```
### Time
`Sys.time()` and `now()` return the date, time and the timezone. In `now()`, we can specify the timezone using the `tzone` argument.
```{r sys_time}
Sys.time()
lubridate::now()
lubridate::now(tzone = "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`
```{r lub_am}
lubridate::am(now())
lubridate::pm(now())
```
### Leap Year
We can also check if the current year is a leap year using `leap_year()`.
```{r leap_year}
lubridate::leap_year(Sys.Date())
```
### Summary
```{r table_current_date_time, echo=FALSE}
cname <- c("`Sys.Date()`", "`lubridate::today()`", "`Sys.time()`",
"`lubridate::now()`", "`lubridate::am()`", "`lubridate::pm()`",
"`lubridate::leap_year()`")
descrip <- c("Current Date", "Current Date", "Current Time", "Current Time",
"Whether time occurs in am?", "Whether time occurs in pm?",
"Check if the year is a leap year?")
data.frame(Function = cname, Description = descrip) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
### Your Turn
- get current date
- get current time
- check whether the time occurs in am or pm?
- check whether the following years were leap years
- 2018
- 2016
## Case Study
Throughout the tutorial, we will work on a case study related to transactions of a imaginary company. The data set includes information about
invoice and payment dates.
### Data
```{r import, eval=FALSE}
transact <- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/transact.csv')
```
```{r show, echo=FALSE, eval=TRUE, message=FALSE}
transact <- readr::read_csv('https://raw.githubusercontent.com/rsquaredacademy/datasets/master/transact.csv')
transact
```
### Data Dictionary
The data set has 3 columns. All the dates are in the format (yyyy-mm-dd).
<br>
<br>
```{r table_data_dict, echo=FALSE}
cname <- c("Invoice", "Due", "Payment")
descrip <- c("Invoice Date", "Due Date", "Payment Date")
data.frame(Column = cname, Description = descrip) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
In the case study, we will try to answer a few questions we have about the `transact` data.
- extract date, month and year from Due
- compute the number of days to settle invoice
- compute days over due
- check if due year is a leap year
- check when due day in february is 29, whether it is a leap year
- how many invoices were settled within due date
- how many invoices are due in each quarter
## Date & Time Classes
### Introduction
In this section, we will look at two things. First, how to create date/time
data in R, and second, how to convert other data types to date/time. Let us
begin by creating the latest R release date manually.
```{r date_manual}
release_date <- 2019-12-12
release_date
```
Okay! Why do we see `1995` when we call the date? What is happening here? Let us
quickly check the data type of `release_date`.
```{r date_type}
class(release_date)
```
The data type is `numeric` i.e. R has subtracted `12` twice from `2019` to
return `1995`. Clearly, the above method is not the right way to store
date/time. Let us see if we can get some hints from the builtin R functions we
used in the previous section. If you observe the output, all of them returned
date/time wrapped in quotes. Hmmm... let us wrap our date in quotes and see what
happens.
```{r date_wrap}
release_date <- "2019-12-12"
release_date
```
Alright, now R does not do any arithmetic and returns the date as we specified.
Great! Is this the right format to store date/time? No. Why? What is the problem
if date/time is saved as character/string? The problem is the nature or type of
operations done on date or time is different when compared to string/character,
number or logical values.
- how do we add/subtract dates?
- how do we extract components such as year, month, day etc.
To answer the above questions, we will first check the data type of `Sys.Date()`
and `now()`.
```{r check_date_type}
class(Sys.Date())
class(lubridate::now())
class(release_date)
```
As you can see from the above output, there are 3 different classes for storing
date/time in R
- `Date`
- `POSIXct`
- `POSIXlt`
Let us explore each of the above classes one by one.
### Date
#### Introduction
The `Date` class represents calendar dates. Let us go back to `Sys.Date()`. If
you check the class of `Sys.Date()`, it is `Date`. Internally, this date is a
number i.e. an integer. The `unclass()` function will show dates are stored
internally.
```{r unclass_sys_date}
unclass(Sys.Date())
```
What does this integer represent? Why has R stored the date as an integer?
Before we answer this question, we need to know something else. In R, dates are
represented as the number of days since `1970-01-01`. All the dates in R are
internally stored in this way. Before we explore this concept further, let us
learn to create `Date` objects in R. We will continue to use the latest R
release date, `2019-12-12`.
Until now, we have stored the above date as character/string but now we will use
`as.Date()` to save it as a `Date` object. `as.Date()` is the easiest and
simplest way to create dates in R.
```{r release_as_date}
release_date <- as.Date("2019-12-12")
release_date
```
The `as_date()` function from the lubridate package is similar to `as.Date()`.
```{r release_date_lubridate}
release_date <- lubridate::as_date("2019-12-12")
release_date
```
If you look at the difference between `release_date` and `1970-01-01`, it will
be the same as `unclass(release_date)`.
```{r release_date_unclass}
release_date - as.Date("1970-01-01")
unclass(release_date)
```
Let us come back to `1970-01-01` i.e. the origin for dates in R.
```{r origin}
lubridate::origin
```
From the previous examples, we know that dates are internally stored as number
of days since `1970-01-01`. How about dates older than the origin? How are they
stored? Let us look at that briefly.
```{r older_than_origin}
unclass(as.Date("1963-08-28"))
```
Dates older than the origin are stored as negative integers. For those who are
not aware, Martin Luther King, Jr. delivered his famous **I Have a Dream**
speech on `1963-08-28`. Let us move on and learn how to convert numbers into
dates.
#### Convert Numeric
The `as.Date()` function can be used to convert any of the following to a `Date`
object
- character/string
- number
- factor (categorical/qualitative)
We have explored how to convert strings to date. How about converting numbers to
date? Sure, we can create date from numbers by specifying the origin and number
of days since it.
```{r release_date_origin}
as.Date(18242, origin = "1970-01-01")
```
The origin can be changed to another date (while changing the number as well.)
```{r release_date_diff_origin}
as.Date(7285, origin = "2000-01-01")
```
### ISO 8601
```{r img1lub, fig.align='center', echo=FALSE}
knitr::include_graphics('img/iso.png')
```
If you have carefully observed, the format in which we have been specifying the
dates as well as of those returned by functions such as `Sys.Date()` or
`Sys.time()` is the same i.e. `YYYY-MM-DD`. It includes
- the year including the century
- the month
- the date
The month and date separated by `-`. This default format used in R is the ISO
8601 standard for date/time. ISO 8601 is the internationally accepted way to
represent dates and times and uses the 24 hour clock system. Let us create the
release date using another function `ISOdate()`.
```{r iso_date}
ISOdate(year = 2019,
month = 12,
day = 12,
hour = 8,
min = 5,
sec = 3,
tz = "UTC")
```
We will look at all the different weird ways in which date/time are specified in
the real world in the [Date & Time Formats] section. For the time being, let us
continue exploring date/time classes in R. The next class we are going to look
at is `POSIXct/POSIXlt`.
### POSIX
You might be wondering what is this POSIX thing? POSIX stands for **P**ortable
**O**perating **S**ystem **I**nterface. It is a family of standards specified f
or maintaining compatibility between different operating systems. Before we
learn to create POSIX objects, let us look at `now()` from lubridate.
```{r now_class}
class(lubridate::now())
```
`now()` returns current date/time as a POSIXct object. Let us look at its
internal representation using `unclass()`
```{r now_unclass}
unclass(lubridate::now())
```
The output you see is the number of seconds since January 1, 1970.
#### POSIXct
`POSIXct` represents the number of seconds since the beginning of 1970 (UTC) and
`ct` stands for calendar time. To store date/time as `POSIXct` objects, use
`as.POSIXct()`. Let us now store the latest R release date as `POSIXct` as shown
below
```{r release_date_posixct}
release_date <- as.POSIXct("2019-12-12 08:05:03")
class(release_date)
unclass(release_date)
```
#### POSIXlt
`POSIXlt` represents the following information in a list
- seconds
- minutes
- hour
- day of the month
- month
- year
- day of week
- day of year
- daylight saving time flag
- time zone
- offset in seconds from GMT
The `lt` in `POSIXlt` stands for local time. Use `as.POSIXlt()` to store
date/time as `POSIXlt` objects. Let us store the release date as a `POSIXlt`
object as shown below
```{r release_date_posixlt_1}
release_date <- as.POSIXlt("2019-12-12 08:05:03")
release_date
```
As we said earlier, `POSIXlt` stores date/time components in a list and these
can be extracted. Let us look at the date/time components returned by `POSIXlt`
using `unclass()`.
```{r release_date_posixlt_2}
release_date <- as.POSIXlt("2019-12-12 08:05:03")
unclass(release_date)
```
Use `unlist()` if you want the components returned as a `vector`.
```{r release_date_posixlt_3}
release_date <- as.POSIXlt("2019-12-12 08:05:03")
unlist(release_date)
```
To extract specific components, use `$`.
```{r release_date_posixlt_4}
release_date <- as.POSIXlt("2019-12-12 08:05:03")
release_date$hour
release_date$mon
release_date$zone
```
Now, let us look at the components returned by `POSIXlt`. Some of them are
intuitive
```{r table_posixlt_1, echo=FALSE}
cname <- c("`sec`", "`min`", "`hour`", "`mon`", "`zone`", "`wday`", "`mday`", "`year`", "`yday`", "`isdst`", "`gmtoff`")
descrip <- c("Second", "Minute", "Hour of the day", "Month of the year (0-11",
"Timezone", "Day of week", "Day of month","Years since 1900",
"Day of year", "Daylight saving flag",
"Offset is seconds from GMT")
data.frame(Component = cname, Description = descrip) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
Great! We will end this section with a few tips/suggestions on when to use
`Date` or `POSIXct/POSIXlt`.
- use `Date` when there is no time component
- use `POSIX` when dealing with time and timezones
- use `POSIXlt` when you want to access/extract the different components
### Your Turn
R 1.0.0 was released on `2000-02-29 08:55:23 UTC`. Save it as
- `Date` using character
- `Date` using origin and number
- `POSIXct`
- `POSIXlt` and extract
- month day
- day of year
- month
- zone
- ISODate
## Date Arithmetic
### Introduction
Time to do some arithmetic with the dates. Let us calculate the length of a
course you have enrolled for (Become a Rock Star Data Scientist in 10 Days) by subtracting the course start date from the course end date.
<br>
```{r img2lub, echo=FALSE, out.width="100%", fig.align="center"}
knitr::include_graphics("img/course_duration.png")
```
<br>
```{r lub19, collapse = TRUE}
course_start <- as_date('2017-04-12')
course_end <- as_date('2017-04-21')
course_duration <- course_end - course_start
course_duration
```
### Shift Date
Time to shift the course dates. We can shift a date by days, weeks or months. Let us shift the course start date by:
- 2 days
- 3 weeks
- 1 year
<br>
```{r img3lub, echo=FALSE, out.width="100%", fig.align="center"}
knitr::include_graphics("img/shift_dates.png")
```
<br>
```{r lab40, collapse = TRUE}
course_start + days(2)
course_start + weeks(3)
course_start + years(1)
```
### Case Study
#### Compute days to settle invoice
Let us estimate the number of days to settle the invoice by subtracting the
date of invoice from the date of payment.
```{r lub3}
transact %>%
mutate(
days_to_pay = Payment - Invoice
)
```
#### Compute days over due
How many of the invoices were settled post the due date? We can find this by:
- subtracting the due date from the payment date
- counting the number of rows where delay < 0
```{r lub4}
transact %>%
mutate(
delay = Due - Payment
) %>%
filter(delay < 0) %>%
mutate(
delay = delay * -1
) %>%
count(delay)
```
### Your Turn
- compute the length of a vacation which begins on `2020-04-19` and ends on `2020-04-25`
- recompute the length of the vacation after shifting the vacation start and end date by `10` days and `2` weeks
- compute the days to settle invoice and days overdue from the `receivables.csv` data set
- compute the length of employment (only for those employees who have been terminated) from the `hr-data.csv` data set (use date of hire and termination)
## Time Zones
### Introduction
```{r img_timezones, fig.align='center', out.width="200%", echo=FALSE}
knitr::include_graphics('img/lub_timezones.jpg')
```
In the previous section, `POSIXlt` stored date/time components as a list. Among
the different components it returned were
- `gmtoff`
- `zone`
`gmtoff` is offset in seconds from GMT i.e. difference in hours and minutes from
UTC. Wait.. What do UTC and GMT stand for?
- Coordinated Universal Time (UTC)
- Greenwich Meridian Time (GMT)
Since we are talking about UTC, GMT etc., let us spend a little time on
understanding the basics of time zones and daylight savings.
### Time Zones
Timezones exist because different parts of the Earth receive sun light at
different times. If there was a single timezone, noon or morning would mean
different things in different parts of the world. The timezones are based on
Earth's rotation. The Earth moves ~15 degrees every 60 minutes i.e. 360 degrees
in 24 hours. The planet is divided into 24 timezones each 15 degrees of
longitude width.
Now, you have heard of Greenwich Meridian Time (GMT) right? We just saw GMT off
set in `POSIXlt` and you would have come across it in other time formats as
well. For example, India timezone is given as GMT +5:30. Let us explore GMT in a
little more detail. Greenwich is a suburb of London and the time at Greenwich
is **G**reenwich **M**ean **T**ime. As you move West from Greenwich, every 15
degree section is one hour earlier than GMT and every 15 degree section to the
East is an hour later.
Alright! What is **UTC** then? **C**oordinated **U**niversal **T**ime (UTC) ,
on the other hand, is the time standard commonly used across the world. Even
though they share the same current time, **GMT** is a **timezone** while
**UTC** is a **time standard**.
So how do we check the timezone in R? When you run `Sys.timezone()`, you should
be able to see the timezone you are in.
```{r sys_time_zones}
Sys.timezone()
```
If you do not see the timezone, use `Sys.getenv()` to get the value of the
**TZ** environment variable.
```{r get_time_zone}
Sys.getenv("TZ")
```
If nothing is returned, it means we have to set the timezone. Use `Sys.setenv()`
to set the timezone as shown below. The author resides in India and hence the
timezone is set to `Asia/Calcutta`. You need to set the timezone in which you
reside or work.
```{r set_time_zone}
Sys.setenv(TZ = "Asia/Calcutta")
```
Another way to get the timezone is through `tz()` from the lubridate package.
```{r tz_release_date}
lubridate::tz(Sys.time())
```
If you want to view the time in a different timezone, use `with_tz()`. Let us
look at the current time in **UTC** instead of **Indian Standard Time**.
```{r with_tz}
lubridate::with_tz(Sys.time(), "UTC")
```
### Daylight Savings
```{r img_daylight, fig.align='center', out.width="200%", echo=FALSE}
knitr::include_graphics('img/lub_daylight_savings.png')
```
Daylight savings also known as
- daylight saving time
- daylight savings time
- daylight time
- summer time
is the practice of advancing clocks during summer months so that darkness falls
later each day according to the clock. In other words
- advance clock by one hour in spring (spring forward)
- retard clocks by one hour in autumn (fall back)
In R, the `dst()` function is an indicator for daylight savings. It returns
`TRUE` if daylight saving is in force, `FALSE` if not and `NA` if unknown.
```{r dst}
dst(Sys.Date())
```
### Your Turn
- check the timezone you live in
- check if daylight savings in on
- check the current time in **UTC** or a different time zone
## Date & Time Formats
### Introduction
After the timezones and daylight savings detour, let us get back on path and
explore another important aspect, date & time formats. Although it is a good
practice to adher to ISO 8601 format, not all date/time data will comply with
it. In real world, date/time data may come in all types of weird formats. Below
is a sample
```{r table_formats_sample, echo=FALSE}
cname <- c("December 12, 2019", "12th Dec, 2019", "Dec 12th, 19", "12-Dec-19",
"2019 December", "12.12.19")
data.frame(Format = cname) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
When the data is not in the default ISO 8601 format, we need to explicitly
specify the format in R. We do this using conversion specifications. A
conversion specification is introduced by %, usually followed by a single
letter or O or E and then a single letter.
### Conversion Specifications
```{r table_formats_1, echo=FALSE}
cname <- c("`%d`", "`%m`", "`%b`", "`%B`", "`%y`", "`%Y`", "%H", "%M", "%S")
descrip <- c("Day of the month (decimal number)",
"Month (decimal number)",
"Month (abbreviated)",
"Month (full name)",
"Year (2 digit)",
"Year (4 digit)",
"Hour",
"Minute",
"Second")
example <- c(12, 12, "Dec", "December", 19, 2019, 08, 05, 03)
data.frame(Specification = cname, Description = descrip, Example = example) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
Time to work through a few examples. Let us say you are dealing with dates in
the format `19/12/12`. In this format, the year comes first followed by month
and the date; each separated by a backslash (`/`). The year consists of only 2
digits i.e. it does not include the century. Let us now map each component of
the date to the format table shown at the beginning.
```{r table_formats_ex_1, echo=FALSE}
cname <- c("19", "12", "12")
descrip <- c("`%y`", "`%m`", "`%d`")
data.frame(Date = cname, Specification = descrip) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
Using the format argument, we will specify the date format as a character vector
i.e. enclosed in quotes.
```{r format_examples_1}
as.Date("19/12/12", format = "%y/%m/%d")
```
Another way in which the release data can be written is `2019-Dec-12`. We still
have the year followed by the month and the date but there are a few changes
here:
- the components are separated by a `-` instead of `/`
- year has 4 digits i.e. includes the century
- the month is specified using abbreviation instead of digits
Let us map the components to the format table:
```{r table_formats_ex_2, echo=FALSE}
cname <- c("2019", "Dec", "12")
descrip <- c("`%Y`", "`%b`", "`%d`")
data.frame(Date = cname, Specification = descrip) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
Let us specify the format for the date using the above mapping.
```{r format_examples_2}
as.Date("2019-Dec-12", format = "%Y-%b-%d")
```
In both the above examples, we have not dealt with time components. Let us
include the time of the latest R release in the next one i.e.
`19/12/12 08:05:03`.
```{r table_formats_ex_3, echo=FALSE}
cname <- c("19", "12", "12", "08", "05", "03")
descrip <- c("`%y`", "`%m`", "`%d`", "`%H`", "`%M`", "`%S`")
data.frame(Date = cname, Specification = descrip) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
Since we are dealing with time, we will use `as.POSIXct()` instead of
`as.Date()`.
```{r format_examples_3}
as.POSIXct("19/12/12 08:05:03", tz = "UTC", format = "%y/%m/%d %H:%M:%S")
```
In the below table, we look at some of the most widely used conversion
specifications. You can learn more about these specifications by running
`?strptime` or `help(strptime)`.
```{r table_formats_2, echo=FALSE}
cname <- c("`%a`", "`%A`", "`%C`", "`%D`", "`%e`", "`%F`", "`%h`", "`%I`", "`%j`",
"`%R`", "`%t`", "`%T`", "`%u`", "`%U`", "`%V`", "`%w`", "`%W`")
descrip <- c("Abbreviated weekday",
"Full weekday",
"Century (00-99)",
"Same as `%m/%d/%y`",
"Day of month [1 - 31]",
"Same as `%Y-%m-%d`",
"Same as `%b`",
"Hours as decimal [01 - 12]",
"Day of year [001 - 366]",
"Same as `%H:%M`",
"Tab",
"Same as `%H:%M:%S`",
"Weekday [1 - 7](Monday is 1)",
"Week of year [00 - 53]",
"Week of year [01 - 53]",
"Weekday [0 - 6](sunday is 0)",
"Week of year [00 - 53]")
data.frame(Specification = cname, Description = descrip) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
We have included a lot of practice questions for you to explore the different
date/time formats. The solutions are available in the Learning Management system
as well as in our GitHub repo. Try them and let us know if you have any doubts.
### Guess Format
`guess_formats()` from lubridate is a very useful function. It will guess the
date/time format if you specify the order in which year, month, date, hour,
minute and second appear.
```{r guess_formats}
release_date_formats <- c("December 12th 2019",
"Dec 12th 19",
"dec 12 2019")
guess_formats(release_date_formats,
orders = "mdy",
print_matches = TRUE)
```
### Your Turn
Below, we have specified `July 5th, 2019` in different ways. Create the date using `as.Date()` while specifying the correct format for each of them.
- `July-05-19`
- `JUL-05-19`
- `05.07.19`
- `5-July 2019`
- `July 5th, 2019`
- `July 05, 2019`
- `2019-July- 05`
- `05/07/2019`
- `07/05/2019`
- `7/5/2019`
- `07/5/19`
- `2019-07-05`
## Parse Date & Time
While creating date-time objects, we specified different formats using the
conversion specification but most often you will not create date/time and
instead deal with data thay comes your way from a system or
colleague/collaborator. In such cases, we need to be able to parse date/time
from the data provided to us. In this section, we will focus on parsing
date/time from character data. Both base R and the lubridate package offer
functions to parse date and time and we will explore a few of them in this
section. We will initially use functions from base R and later on explore those
from lubridate which will give us an opportunity to compare and contrast. It
will also allow us to choose the functions based on the data we are dealing
with.
`strptime()` will convert character data to `POSIXlt`. You will use this when
converting from character data to date/time. On the other hand, if you want to
convert date/time to character data, use any of the following:
- `strftime()`
- `format()`
- `as.character()`
The above functions will convert `POSIXct/POSIXlt` to character. Let us start
with a simple example. The data we have been supplied has date/time as
character data and in the format `YYYYMMDD` i.e. nothing separates the year,
month and date from each other. We will use `strptime()` to convert this to an
object of class `POSIXlt`.
```{r strptime_1}
rel_date <- strptime("20191212", format = "%Y%m%d")
class(rel_date)
```
If you have a basic knowledge of conversion specifications, you can use
`strptime()` to convert character data to `POSIXlt`. Let us quickly explore the
functions to convert date/time to character data before moving on to the
functions from lubridate.
```{r}
rel_date_strf <- strftime(rel_date)
class(rel_date_strf)
rel_date_format <- format(rel_date)
class(rel_date_format)
rel_date_char <- as.character(rel_date)
class(rel_date_char)
```
As you can see, all the 3 functions converted date/time to character. Time to
move on and explore the lubridate package. We will start with an example in
which the release date is formatted in 3 different ways but they have one thing
in common i.e. the order in which the components appear. In all the 3 formats,
the year is followed by the month and then the date.
To parse the release date, we will use `parse_date_time()` from lubridate which
parses the input into `POSIXct` objects.
```{r parse_date_time}
release_date <- c("19-12-12", "20191212", "19-12 12")
parse_date_time(release_date, "ymd")
parse_date_time(release_date, "y m d")
parse_date_time(release_date, "%y%m%d")
```
Try to use `strptime()` in the above example and see what happens. Now, let us
look at another data set.
```{r parse_date_time_multiple}
release_date <- c("19-07-05", "2019-07-05", "05-07-2019", "07-05-2019")
```
What happens in the below case? The same date appears in multiple formats. How
do we parse them? `parse_date_time()` allows us to specify mutiple date-time
formats. Let us first map the dates to their formats.
```{r table_formats_pdt, echo=FALSE}
cname <- c("19-07-05", "2019-07-05", "05-07-2019", "07-05-2019")
descrip <- c("`ymd`", "`ymd`", "`dmy`", "`mdy`")
data.frame(Date = cname, Specification = descrip) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
The above specifications can be supplied as a character vector.
```{r parse_date_2}
parse_date_time(release_date, c("ymd", "ymd", "dmy", "mdy"))
```
Great! We have used both `strptime()` and `parse_date_time()` now. Can you tell
what differentiates `parse_date_time()` when compared to `strptime()`? We
summarize it in the points below:
- no need to include `%` prefix or separator
- specify several date/time formats
There are other helper functions that can be used to
- parse dates with year, month, day components
- parse dates with year, month, day, hour, minute, seconds components
- parse period with hour, minute, second components
and are explored in the below examples.
```{r parse_ymd}
# year/month/date
ymd("2019-12-12")
# year/month/date
ymd("19/12/12")
# date/month/year
dmy(121219)
# year/month/date/hour/minute/second
ymd_hms(191212080503)
# hour/minute/second
hms("8, 5, 3")
# hour/minute/second
hms("08:05:03")
# minute/second
ms("5,3")
# hour/minute
hm("8, 5")
```
Note, in a couple of cases where the components are not separated by `/`, `-` or
space, we have not enclosed the values in quotes.
### Your Turn
Below, we have specified `July 5th, 2019` in different ways. Parse the dates using `strptime()` or `parse_date_time()` or any other helper function.
- `July-05-19`
- `JUL-05-19`
- `05.07.19`
- `5-July 2019`
- `July 5th, 2019`
- `July 05, 2019`
- `2019-July- 05`
- `05/07/2019`
- `07/05/2019`
- `7/5/2019`
- `07/5/19`
- `2019-07-05`
## Date & Time Components
In the second section, we discussed the downside of saving date/time as
character/string in R. One of the points we discussed was that we can't extract
components such as year, month, day etc. In this section, we will learn to
extract date/time components such as
- year
- month
- date
- week
- day
- quarter
- semester
- hour
- minute
- second
- timezone
```{r img_day_week_month, fig.align='center', echo=FALSE}
knitr::include_graphics('img/day_week_month.png')
```
The below table outlines the functions we will explore in the first part of this
section.
```{r table_components_1, echo=FALSE}
cname <- c("`year()`", "`month()`", "`month(label = TRUE)`",
"`month(abbr = FALSE)`", "`months()`", "`week()`")
descrip <- c("Get year", "Get month (number)", "Get month (abbreviated name)",
"Get month (full name)", "Get month", "Get week")
data.frame(Function = cname, Description = descrip) %>%
kable() %>%
kable_styling(
bootstrap_options = c("striped", "hover", "condensed", "responsive")
)
```
### Year
```{r year}
release_date <- ymd_hms("2019-12-12 08:05:03")
year(release_date)
```
### Month