1
votes

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.

1
Please share an extract of your data using dput() function with an example of dates well converted and not. - Scipione Sarlo
in any case there is something weird with your third date: timestamp is 9h, 93m(?!?!?), and 16s... - Scipione Sarlo
@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
@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
@MKR In fact one of the two votes is mine ;-) - Scipione Sarlo

1 Answers

3
votes

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.