You are on page 1of 11

Date and Time

Date
Dates
• Dates in R split into:
• dates do not have any time component
• POSIX date-times
• POSIX represents a portable operating system interface
for UNIX
• POSIXct is an integer based storage method – stores
date/time values as number of seconds since January 1,
1970
• POSIXlt is a component based storage method – stores
them as list with elements second, minute, hour, day,
month, and year
Converting to dates
#date
date()
as.Date("2020-8-5")
as.POSIXct("2020-8-5”)
as.POSIXlt("2020-8-5”)

as.Date("2020-8-5 21:15")
as.POSIXct("2020-8-5 21:15")
as.POSIXlt("2020-8-5 21:15")
Using format strings

as.Date("5/8/2020",format="%d/%m/%Y")
as.Date("August 5,2020",format="%B %d,%Y")
as.Date("5Aug20",format="%d%b%y")
Checking class of date

#class
class(as.Date("2020-8-5 21:15"))
class(as.POSIXct("2020-8-5 21:15"))
class(as.POSIXlt("2020-8-5 21:15"))
Strptime()
• strptime() takes a character vector that has
dates and times and converts them into to a
POSIXlt object

datestring<-"August 25, 2021 04:20"


convertedForm<-strptime(datestring,"%B %d, %Y%H:%M")
class(convertedForm)
convertedForm
Getting date, time and zone

#Getting date, time and zone


Sys.Date()
Sys.time()
Sys.timezone()
Getting weekdays & basic arithmetic on dates

d <- as.Date("2020-8-7")
d
weekdays(d)
d+5
d+1:5
weekdays(d+1:5)
Using sequence, getting months & quarters

#using sequence
dt <- seq(d,by="2 months",length.out = 6)
dt
#getting month and quarter
months(d)
months(dt)
quarters(dt)
Create Data Frame

Output

The argument 'stringsAsFactors' is an argument to the 'data. frame()' function in R. It


is a logical that indicates whether strings in a data frame should be treated as factor
variables or as just plain strings.

You might also like