0

I have below date and time values in dataframe, some values are in "/" format and some are in "-" format. How should I standardize the format and keep it "DD-MM-YYYY HH:MM:SS". Also in time in some cases seconds values are not there. Any suggestions ?

Datime$Day
11/7/2016 11:51
11/7/2016 17:57
12/7/2016 9:17
12/7/2016 21:08
13-07-2016 08:33:16
13-07-2016 21:57:28
14-07-2016 06:15:32
15-07-2016 05:11:52
15-07-2016 17:57:27
MrFlick
  • 195,160
  • 17
  • 277
  • 295

2 Answers2

2

One option is parse_date_time from lubridate to match multiple patterns and convert it to a datetime class

library(lubridate)
parse_date_time(Datime$Day, c("%d/%m/%Y %H:%M", "%d-%m-%Y %H:%M:%S"))
#[1] "2016-07-11 11:51:00 UTC" "2016-07-11 17:57:00 UTC"
#[3] "2016-07-12 09:17:00 UTC" "2016-07-12 21:08:00 UTC"
#[5] "2016-07-13 08:33:16 UTC" "2016-07-13 21:57:28 UTC"
#[7] "2016-07-14 06:15:32 UTC" "2016-07-15 05:11:52 UTC"
#[9] "2016-07-15 17:57:27 UTC"

Another option is anytime (if the formats are not already found in the default format list getFormats(), add the new format with addFormats())

library(anytime)
addFormats( c("%d/%m/%Y %H:%M", "%d-%m-%Y %H:%M:%S"))
anytime(Datime$Day)

data

Datime <- structure(list(Day = c("11/7/2016 11:51", "11/7/2016 17:57", 
"12/7/2016 9:17", "12/7/2016 21:08", "13-07-2016 08:33:16", 
   "13-07-2016 21:57:28", 
"14-07-2016 06:15:32", "15-07-2016 05:11:52", "15-07-2016 17:57:27"
)), .Names = "Day", 
   class = "data.frame", row.names = c(NA, -9L
))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Thank you very much Akrun for your kind help. It's working properly. – Suraj Kumar Talreja Jun 04 '18 at 20:25
  • 1
    @SurajKumarTalreja If this answered your question, please upvote and accept the answer (checkmark at top). – G5W Jun 04 '18 at 20:29
  • 2
    Yes @SurajKumarTalreja, rather than thanks, you should **accept it**. Have a look to https://stackoverflow.com/help/someone-answers and https://stackoverflow.com/help/accepted-answer – Marco Jun 04 '18 at 20:53
1

using the base library:

strptime(paste0(gsub("/","-",Datime$Day),":00"),"%d-%m-%Y %H:%M:%S","UTC") 
[1] "2016-07-11 11:51:00 UTC" "2016-07-11 17:57:00 UTC"
[3] "2016-07-12 09:17:00 UTC" "2016-07-12 21:08:00 UTC"
[5] "2016-07-13 08:33:16 UTC" "2016-07-13 21:57:28 UTC"
[7] "2016-07-14 06:15:32 UTC" "2016-07-15 05:11:52 UTC"
[9] "2016-07-15 17:57:27 UTC"
Onyambu
  • 67,392
  • 3
  • 24
  • 53