简体   繁体   中英

R How to convert date format

I was looking to convert the following character string in a date format:

string <- '22APR2020'
date <- as.Date(string, format='%d%b%y')
date
>>> NA

Unfortunately, the result is NA and I need to convert it as a date in order to being able to calculate the time between two dates.

Thanks you

You could use the anytime package:

library(anytime)
string <- '22APR2020'
anytime::anydate(string)
[1] "2020-04-22"

The problem is your locale setting. It probably is set to a language where the fourth month is not abbreviated as "APR".

Sys.setlocale("LC_TIME", "French")

string <- '22APR2020'
as.Date(string, format='%d%b%Y')
#[1] NA

Sys.setlocale("LC_TIME", "German")
as.Date(string, format='%d%b%Y')
#[1] "2020-04-22"

Also, note the capital Y is used in the format string. It's important. y only refers to the decade (it would give the same result, by chance, for 2020, but give the wrong result for 2021).

When in doubt always use lubridate :

string <- '22APR2020'
library(lubridate)
dmy(string)
[1] "2020-04-22"

here dmy is order of date, month and year appearance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM