-1

Hi I have the below dataframe, in which few dates have "dd-mm-yyyy hh:mm" format and few "mm/dd/yyyy hh:mm". However i want to change all to "mm/dd/yyyy hh:mm" format

Below, "02-05-2018 07:45" is in "dd-mm-yyyy hh:mm" format. Which means, 2nd of May. I need it to be converted to 5th of Feb i.e "02/05/2018 07:45" which is in mm/dd/yyyy hh:mm" format

Input :

 Date / Time        Object Value
 02-05-2018 07:45   30
 02-05-2018 08:00   0
 1/30/2018 22:30    65.125
 1/30/2018 22:45    0
 1/30/2018 23:00    58

Output :

 Date / Time        Object Value
 02/05/2018 07:45   30
 02/05/2018 08:00   0
 1/30/2018 22:30    65.125
 1/30/2018 22:45    0
 1/30/2018 23:00    58
Anagha
  • 3,073
  • 8
  • 25
  • 43

2 Answers2

0

If your Date / Time is a character you can get desired datetime in POSIXct format:

library(lubridate)
mdy_hm("02-05-2018 07:45")

or in character format:

library(lubridate)
as.character(mdy_hm("02-05-2018 07:45"))
Antonios
  • 1,919
  • 1
  • 11
  • 18
0

We can use anytime to convert multiple formats to 'DateTime' object

anytime::anytime(df1[,1])
#[1] "2018-02-05 07:45:00 IST" "2018-02-05 08:00:00 IST" "2018-01-30 22:30:00 IST" 
#[4] "2018-01-30 22:45:00 IST" "2018-01-30 23:00:00 IST"

It is better to keep in the date time class instead of changing to a different format. But, it can changed with format

format(anytime::anytime(df1[,1]), "%m/%d/%Y %H:%M")
#[1] "02/05/2018 07:45" "02/05/2018 08:00" "01/30/2018 22:30" 
#[4] "01/30/2018 22:45" "01/30/2018 23:00"

data

df1 <- structure(list(DateTime = c("02-05-2018 07:45", "02-05-2018 08:00", 
"1/30/2018 22:30", "1/30/2018 22:45", "1/30/2018 23:00"), ObjectValue = c(30, 
0, 65.125, 0, 58)), .Names = c("DateTime", "ObjectValue"),
   class =  "data.frame", row.names = c(NA, -5L))
akrun
  • 874,273
  • 37
  • 540
  • 662