简体   繁体   English

日期为两位数的年份

[英]as.Date with two-digit years

If I convert the date 10.10.61 (DD.MM.YY) with as.Date(date, format="%d.%m.%y") for some reason it converts it into 2061 -10-10 . 如果出于某种原因将日期10.10.61 (DD.MM.YY)转换为as.Date(date, format="%d.%m.%y") ,则会将其转换为2061 -10-10

Is there an elegant way to correct for this or do I have to do it manually by slicing the string and adding "19" in front? 是否有一种优雅的方法可以纠正此问题,或者我必须手动将其切成薄片并在前面加上“ 19”吗?

I've also tried the zoo package which brings up the same (wrong) result. 我还尝试了Zoo程序包,该程序带来了相同(错误)的结果。

x = format(as.Date("10.10.61", "%d.%m.%y"), "19%y-%m-%d")
x = as.Date(x)
x
class(x)

Note that a single sub will slice the string and prepend the year with 19 so it is not so onerous: 请注意,单个sub将对字符串进行切片,并在年份前加上19,因此它并不繁琐:

as.Date(sub("(..)$", "19\\1", date), "%d.%m.%Y")
## [1] "1961-10-10"

chron Alternately, the chron package defaults to a cutoff of 30 so it will use 1961 by default: chron可选地,chron软件包的默认截止日期为30,因此默认情况下将使用1961:

library(chron)
as.Date(dates(date, format = "d.m.y"))
## [1] "1961-10-10"

In chron the year expansion rule is defined by the "chron.year.expand" option which by default is set to the year.expand function and that function's default cut.off is 30. See this SO post for more info: Add correct century to dates with year provided as "Year without century", %y 在chron中,年份扩展规则由"chron.year.expand"选项定义,该选项默认设置为year.expand函数,该函数的默认cut.off为30。有关更多信息,请参cut.off SO帖子: 添加正确的世纪迄今提供的年份为“无世纪年份”,%y

If all your dates in 1900s, then you can use this solution: 如果您所有的日期都在1900年代,那么您可以使用以下解决方案:

library(magrittr)
your_date = '10.10.61'
as.Date(your_date,format="%d.%m.%y") %>% format("19%y%m%d") %>% as.Date("%Y%m%d")

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

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