简体   繁体   English

将 R fread 中的字符日期转换为显示四位数年份格式

[英]Convert character date in R fread to show four digit year format

I have a csv file which shows date as 14-Mar-20 .我有一个 csv 文件,它显示日期为 14-Mar-20 。 Its a Date-Month-Year format.它是一种日期-月-年格式。 But in background it is showing as 3/14/2020.但在后台显示为 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).当我尝试将这个文件 fread 到 R 时,它作为字符格式 14-Mar-20.I 将其转换为日期 as.Date(x, format("%d-%h-%Y)。

The issue is, In R the date shows the year as "20" (Two digits).问题是,在 R 中,日期将年份显示为“20”(两位数)。 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.我想将数据作为四位数年份读入 R。我不想添加字符串 20 使其成为 2020 年,因为也可以有像 1948 年这样的年份。没有多少格式有助于年份为 %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?有没有一种方法可以读取 csv 文件,使得日期为 14/Mar/2020 或在 R 中的一种方法,可以将年份变成四位数字而无需将 20 字符串添加到年份?

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.您想使用 %y。

From the documentation of strptime() :strptime()的文档中:

Year without century (00–99).没有世纪的年份 (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'.在输入时,值 00 到 68 以 20 为前缀,69 到 99 以 19 为前缀——这是 2018 POSIX 标准指定的行为,但它也说“预计在未来版本中,默认世纪是从 2 -数字年份会改变'。

You can use as.Date to convert dates into date class.您可以使用as.Date将日期转换为日期类。

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.如果您想要特定格式的数据,请使用日期值的format

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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