kinsgter24
kinsgter24

Reputation: 39

How to convert Date and time format in r?

I am having a dataset that looks like this :

Mno    Date and time      value
123 23-01-2021 08:03:04     23
234 23-01-2021 08:03:04     25
345 23-01-2021 08:03:04     26
456 23-01-2021 08:03:04     27

I want only time to be in 00:00:00

Mno Date and time       value
123 23-01-2021 00:00:00  23
234 23-01-2021 00:00:00  25
345 23-01-2021 00:00:00  26
456 23-01-2021 00:00:00  27

Thanks in advance

Upvotes: 1

Views: 189

Answers (3)

Ronak Shah
Ronak Shah

Reputation: 389315

You can use sub to do this via regex -

df$Date <- sub('\\d+:\\d+:\\d+', '00:00:00', df$Date)
df

#  Mno                Date value
#1 123 23-01-2021 00:00:00    23
#2 234 23-01-2021 00:00:00    25
#3 345 23-01-2021 00:00:00    26
#4 456 23-01-2021 00:00:00    27

Upvotes: 1

Sandwichnick
Sandwichnick

Reputation: 1466

Using lubridate:

yourdataframe$`Date and Time` <- update(yourdataframe$`Date and Time`,hour=0, minute=0, second=0)

it might seem that it only rembers the date, but this is formatting quirk of the PosiXct.

it will calculate the timeline correct. To demonstrate, this will be the Datetime Vector if we add an hour to the datetime:

yourdataframe$`Date and Time` <- yourdataframe$`Date and Time`+ hours(1)
yourdataframe$`Date and Time`
#[1] "2021-01-23 01:00:00 UTC"
#[2] "2021-01-23 01:00:00 UTC"
#[3] "2021-01-23 01:00:00 UTC"
#[4] "2021-01-23 01:00:00 UTC"

Upvotes: 1

denis
denis

Reputation: 5673

You can use the package lubridate:

library(lubridate)
library(magrittr)


df$Date <- dmy_hms(df$Date) %>%
  as_date() %>%
  format.Date("%d-%m-%Y %H:%M:%S") 

  Mno                Date value
1 123 23-01-2021 00:00:00    23
2 234 23-01-2021 00:00:00    25
3 345 23-01-2021 00:00:00    26
4 456 23-01-2021 00:00:00    27

as_date keep only the date, that you reformat with the 00 for the time with format.Date


data:

df <- read.csv(text = "
Mno    ;Date      ;value
123   ;23-01-2021 08:03:04;     23
234   ;23-01-2021 08:03:04;     25
345   ;23-01-2021 08:03:04;     26
456   ;23-01-2021 08:03:04;     27",sep = ";")

Upvotes: 0

Related Questions