Extract year, month, day and week from date string using lubridate library
Parag Verma
6th April, 2022
Introduction
In this blog we will look at how year, month and date components can be extracted from date string using lubridate library
package.name<-c("dplyr","stringr","lubridate")
for(i in package.name){
if(!require(i,character.only = T)){
install.packages(i)
}
library(i,character.only = T)
}
Step 1: Creating dummy date vector
dt_val<-c("2015-4")
dt_val
[1] "2015-4"
Step 2: Converting into Date format
For any date string to be converted into a date, it has to have year, month and date information.If the date string doesnt have these, then we add based on the following rules:
Rules:
- If there is no date information available, then we add 15(middle of the month) to the string
- If there is no month information available, then we add 06(middle of the year) to the string
- If there is no month and date information available, then we add 06(middle of the year) and 15(middle of the month)to the string
Step 3: Converting a date with just year and date information available
dt_val
[1] "2015-4"
Adding June month to the date
dt_val1<-str_c(dt_val,"-06")
dt_val1
[1] "2015-4-06"
year_date_only<-as.Date(dt_val1,"%Y-%d-%m")
year_date_only
[1] "2015-06-04"
The above date represents 4th June 2015
Step 4A: Extracting Year Information from the date
year(year_date_only)
[1] 2015
Step 4B: Extracting month Information from the date
month(year_date_only)
[1] 6
Step 4C: Extracting date Information from the date
day(year_date_only)
[1] 4
Step 4C: Extracting week Information from the date
week(year_date_only)
[1] 23
Parting Comments
In this blog we looked at how we can leverage lubrudate library to extract year, month, day and week information from a date string
R Complete Guide
Python Complete Guide
https://www.aimlmadeeasy.com/2021/09/python-complete-guide.html