在 as.Date() 中使用 "format" 参数

Using the "format" argument in as.Date()

我正在尝试使用 R 中的 as.Date() 将“07,29,30”转换为日期格式。

(注意字符串格式为"mm,dd,yy",即1930年7月29日)

所以我使用了以下代码:

as.Date("07,29,30", format = "%m,%d,%y")

但是我返回的年份是 2030 年,而不是 1930 年。 我怎样才能告诉 R 将值转换为一个世纪前的日期?

无论如何我都会加入:

# use this library
library(lubridate)

# convert to the format (your way or you acn use lubridate)
dateconvert <- as.Date("07,29,30", format = "%m,%d,%y") 

# get the year
inputYear <- year(dateconvert)

# convert the year
year(dateconvert) <- ifelse(inputYear > 2000, 1900 + (inputYear %% 100), inputYear)

要解决此问题,请使用 strtotime()date():

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

因为 00 到 68 之间的年份值被编码为 20 世纪。 从 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 2004 and 2008 POSIX standards, but they do also say ‘it is expected that in a future version the default century inferred from a 2-digit year will change’."

您可以使用下面的代码重新编码。

d <- as.Date("07,29,30", format = "%m,%d,%y")

> as.Date(ifelse(d > today(), format(d, "19%y-%m-%d"), format(d)))
[1] "1930-07-29"

尝试以下操作: 格式 (as.Date("07,29,30", 格式 = "%m,%d,%y"), "19%y-%m-%d")