Home > Software design >  How to change a column of characters into date form?
How to change a column of characters into date form?

Time:03-11

I currently have data as such: data

I wish to change the 'date' column to date type. (it is now in character).

I have tried the code below but it gives me 'NA' as the result.

as.Date(data$Date, format = "%a %d-%m-%Y %I:%M %p")

Am I making a mistake in the way I am formatting the date to suit the format in my data?

CodePudding user response:

Unfortunately, we don't have your data (we have a picture of your data, but the only way to use that is to transcribe it manually - best to include data as text in your questions).

Anyway, using a brief example in the same format:

dates <- c("Wed 25-Apr-2018 3:20 PM", "Thu 10-Mar-2022 10:53 AM")

We can get the dates by doing:

as.Date(dates, "%a %d-%b-%Y %I:%M %p")
#> [1] "2018-04-25" "2022-03-10"

Note though that this does not preserve the time, and to do this you probably want to use R's built in date-time format, POSIXct. We can get this with:

strptime(dates, "%a %d-%b-%Y %I:%M %p")
#> [1] "2018-04-25 15:20:00 BST" "2022-03-10 10:53:00 GMT"

I think the main problem was that you were using %m for the month, but this only parses months in decimal number format. You need %b for text-abbreviations of months.

  • Related