1

I have two different dates in a data.frame in the following format as factors "dd-mm-yyyy HH:MM:SS" and "dd/m/yyyy hh:mm" and I'm trying to convert this into the same format using the strptime:

strptime(x = as.character(data.frame$timestamp),format = "%d/%m/%Y %H:%M:%S") 

but only "dd/m/yyyy hh:mm" is converting and the other timestamp results in NA.

m0nhawk
  • 22,980
  • 9
  • 45
  • 73
user2310119
  • 35
  • 1
  • 4
  • Please share an extract of your data using `dput()` function with an example of dates well converted and not. – Scipione Sarlo Jan 07 '18 at 10:00
  • test<-data.frame("12/7/2008 11:21", "12/7/2008 21:08","23-09-2008 09:93:16","14-07-2008 21:57:28") strptime(x = as.character(test),format = "%d/%m/%Y %H:%M:%S") – user2310119 Jan 07 '18 at 10:11
  • output as Na Na Na Na – user2310119 Jan 07 '18 at 10:13
  • I think the problem is more concerning with the separator than the digits of months. In fact, when you have only a digit for month you have `/` as separator, and when you have two digits you have `-` as separator. Here you may find the solution to your problem: https://stackoverflow.com/questions/13764514/how-to-change-multiple-date-formats-in-same-column – Scipione Sarlo Jan 07 '18 at 10:26
  • 1
    in any case there is something weird with your third date: timestamp is 9h, 93m(?!?!?), and 16s... – Scipione Sarlo Jan 07 '18 at 10:45
  • @ScipioneSarlo That date is invalid in example. It should be corrected before trying solution. I have modified it be a valid date in answer. – MKR Jan 07 '18 at 10:52
  • 1
    @MKR I suppose too, but I think it's better to give him a code with its real data so when the parsing function (base R or `lubridate`) returns NAs he may consider whether (and how) to correct the real data he has to wrangle with. – Scipione Sarlo Jan 07 '18 at 10:56
  • 1
    @scipioneSarlo yes. You have already pointed out it to him and I'll modify my answer to use data from OP. I thought it could be typo in OP. – MKR Jan 07 '18 at 11:01
  • 1
    @MKR In fact one of the two votes is mine ;-) – Scipione Sarlo Jan 07 '18 at 11:03

1 Answers1

3

I'm not sure about your end goal. But you can use lubridate package to convert vector containing dates in mixed formats.

library(lubridate)
test<-data.frame(timestamp = c("12/7/2008 11:21", "12/7/2008 21:08",
"23-09-2008 09:13:16","14-07-2008 21:57:28"))
dates_df <- parse_date_time(test$timestamp, c("dmy HMS", "dmy HM"))
#>dates_df
#[1] "2008-07-12 11:21:00 UTC" "2008-07-12 21:08:00 UTC"
"2008-09-23 09:13:16 UTC" "2008-07-14 21:57:28 UTC"

Dates are converted and available in dates_df which can be converted or used per choice.

MKR
  • 19,739
  • 4
  • 23
  • 33