How to convert a date from a character string?

2020-01-29 03:09发布

I have searched but I could not find out how to convert a date from a character string formatted as follows:

date <- "07-21-2015-09:30AM"

I wanted to use as.Date, but I have not manage to. All I get is the following:

as.Date(date, format="%m-%d-%y-%hAM")
NA

as.Date(dates, format="%m-%d-%y-%h")
NA

标签: r date
3条回答
家丑人穷心不美
2楼-- · 2020-01-29 03:18

I like strptime for this:

strptime(date, format="%m-%d-%Y-%R%p")
#[1] "2015-07-21 09:30:00 EDT"

And in the case that you needed to see the date in the same format as entered, you can call the related strftime. It doesn't change the internal storage of the variable, rather it changes the format only.

strftime(xx, format="%m-%d-%Y-%R%p")
#[1] "07-21-2015-09:30AM"
查看更多
迷人小祖宗
3楼-- · 2020-01-29 03:25

If we need the 'date' and 'time', one option is as.POSIXct

 as.POSIXct(date, format='%m-%d-%Y-%I:%M%p')
 #[1] "2015-07-21 09:30:00 EDT"
查看更多
对你真心纯属浪费
4楼-- · 2020-01-29 03:38

You can also use the lubridate package like this:

library('lubridate')
date <- "07-21-2015-09:30AM"
mdy_hm(date)
# "2015-07-21 09:30:00 UTC"
查看更多
登录 后发表回答