Extract date from timestamp in R

In Order to extract date from timestamp in R we will be using Format() function. Let’s see how to get date from timestamp in R with an example.

Let’s first create the dataframe.

### Create Data Frame

df1 = data.frame (
  Name =c('Annie','Catherine','Teresa','Peterson','Richard','joe'),
  Login_time = as.POSIXct(c('2018-06-03 19:40:00','2018-06-03 11:30:30','2018-06-03 2:04:13','2018-06-03 16:44:43','2018-06-03 7:14:43','2018-06-03 17:12:41')),
  Logout_time = as.POSIXct(c('2018-06-03 21:40:34','2018-06-03 12:40:10','2018-06-03 3:44:23','2018-06-03 17:34:13','2018-06-03 9:34:23','2018-06-03 18:32:41')))
df1

dataframe df1 will be

Get date from time stamp in R 1

 

Extract date from timestamp in R

Method 1:

Date is extracted from timestamp (column: Logout_time) using Format() function as shown below.

df1$date_component <- format(df1$Logout_time,'%Y-%m-%d')
df1

So the resultant data frame has a column date_component with date extracted from timestamp.

Get date from time stamp in R 2

Method 2:

Another method to get date from timestamp in R, is simple usage of as.Date() function over Logout_time as shown below

df1$date_component <- as.Date(df1$Logout_time)
df1

So the resultant data frame has a column date_component with date extracted from timestamp.

Get date from time stamp in R 3