I have a csv file which shows date as 14-Mar-20 . Its a Date-Month-Year format. But in background it is showing as 3/14/2020.
When I try to do fread this file into R it comes as a character format 14-Mar-20.I converted this to date as as.Date(x, format("%d-%h-%Y).
The issue is, In R the date shows the year as "20" (Two digits). I want to read the data as four digit year into R. I don't want to add string 20 to make it 2020 as there can also have years like 1948. No amount of formatting helps with Year as %Y.
Is there a way to read csv file such that the date comes as 14/Mar/2020 or a way in R to make the years into four digit without string add of 20 to year?
Sample Data
c("12-Dec-14", "19-Dec-14", "12-Dec-14", "19-Dec-14", "12-Dec-14",
"26-Dec-14")
Expected Output:
12-12-2014, 19-Dec-2014....
Note: In csv file it is stores as 12/12/2014 but formatted to show as 12-Dec-14. So when I pull the data in R it comes as 12-Dec-14
Maybe this could help
> strftime(as.Date(d,format = "%d-%b-%y"),format = "%d-%b-%Y")
[1] "12-Dec-2014" "19-Dec-2014" "12-Dec-2014" "19-Dec-2014" "12-Dec-2014"
[6] "26-Dec-2014"
Data
d <- c("12-Dec-14", "19-Dec-14", "12-Dec-14", "19-Dec-14", "12-Dec-14",
"26-Dec-14")
You want to use %y.
From the documentation of strptime()
:
Year without century (00–99). On input, values 00 to 68 are prefixed by 20 and 69 to 99 by 19 – that is the behaviour specified by the 2018 POSIX standard, but it does also say 'it is expected that in a future version the default century inferred from a 2-digit year will change'.
You can use as.Date
to convert dates into date class.
x <- c("12-Dec-14", "19-Dec-14", "12-Dec-14", "19-Dec-14", "12-Dec-14", "26-Dec-14")
x1 <- as.Date(x, '%d-%b-%y')
x1
#[1] "2014-12-12" "2014-12-19" "2014-12-12" "2014-12-19" "2014-12-12" "2014-12-26"
If you want data in specific format use format
on date values.
x2 <- format(x1, '%d-%b-%Y')
x2
#[1] "12-Dec-2014" "19-Dec-2014" "12-Dec-2014" "19-Dec-2014" "12-Dec-2014" "26-Dec-2014"
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.