Junior Data Scientist
Junior Data Scientist

Reputation: 11

Proper date formatting in R

I am currently working with this dataset.

'data.frame':   2938 obs. of  4 variables:
  $ X                     : int  21562 21603 21618 21620 21659 21990 21996 22024 22592 22665 ...
  $ uuid                  : Factor w/ 2938 levels "0005d695-6bc8-48ad-b323-803499630e43",..: 2396 2910 2372 2008 2582 1405 2114 1447 2348 2503 ...
  $ date                  : Factor w/ 2927 levels "2015-06-06T06:33:14Z",..: 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 ...
  $ type                  : Factor w/ 1 level "productCart": 1 1 1 1 1 1 1 1 1 1 ...

There is a variable date here, where date is in this format:

date --> 2015-06-06T06:33:14Z

I want to create a new variable and change date into a more workable format which should look like that:

NewDate --> 2015-06-06 06:33:14

Could you please give me any advice? I am trying few different approaches and none of them works so far.

Upvotes: 1

Views: 59

Answers (1)

akrun
akrun

Reputation: 887811

You can use as.POSIXct to convert to 'POSIXct' class

  date1 <- as.POSIXct(date, format='%Y-%m-%dT%H:%M:%SZ')
  date1
  #[1] "2015-06-06 06:33:14 EDT"

Or using lubridate

  library(lubridate)
  ymd_hms(date, tz='EDT')
  #[1] "2015-06-06 06:33:14 EDT"

If we want to extract the hour and minute part, format can be used

 format(date1, '%H:%M')
 #[1] "06:33"

data

   date <- "2015-06-06T06:33:14Z"

Upvotes: 1

Related Questions