问题
I have some data that looks like this:
dates <- structure(c(1L, 2L, 4L, 3L), .Label = c("Sat, 18 Nov 2017 00:00:00 GMT",
"Thu, 16 Nov 2017 00:00:00 GMT", "Tue, 14 Nov 2017 00:00:00 GMT",
"Wed, 15 Nov 2017 00:00:00 GMT"), class = "factor")
I would like to convert it to a date format instead of having it as a factor. Additionally, I want to strip the 00:00:00 GMT because it is meaningless
I tried lubridate
but I'm having troubles with the format:
library(lubridate)
mdy(dates)
Warning message:
All formats failed to parse. No formats found.
回答1:
This looks like it is working:
as.POSIXct(dates, format = '%a, %d %b %Y %H:%M:%S')
#[1] "2017-11-18 GMT" "2017-11-16 GMT" "2017-11-15 GMT" "2017-11-14 GMT"
回答2:
We can also use dmy_hms
from the lubridate
package.
library(lubridate)
dmy_hms(dates, tz = "GMT")
# [1] "2017-11-18 GMT" "2017-11-16 GMT" "2017-11-15 GMT" "2017-11-14 GMT"
回答3:
Use as.Date
like this. It ignores junk at the end so this works. No packages are used.
as.Date(dates, "%a, %d %b %Y")
## [1] "2017-11-18" "2017-11-16" "2017-11-15" "2017-11-14"
来源:https://stackoverflow.com/questions/47366703/convert-to-date-and-strip-time