r中的格式日期转换
Format date conversion in r
我正在尝试读取包含一些日期变量的 excel 文件。但是当我使用该函数读取文件并显示变量时,我的两个变量的格式不同,如下例所示。
date1
[1] "2009-05-22 UTC" "1995-09-13 UTC" "1996-03-20 UTC" "2006-17-05 UTC" "2005-09-25 UTC" "2004-12-15 UTC" NA NA "1997-05-30 UTC"
date2
[1] "2016-05-07 08:57:00 UTC" "2014-07-22 19:01:00 UTC" "2018-12-02 12:14:00 UTC" "2020-01-11 13:27:00 UTC" "2013-14-21 11:40:00 UTC"
[6] "2019-08-15 09:31:00 UTC" NA NA "2016-07-23 00:00:00 UTC"
如何将 date2 的格式转换为 date1 的格式
您可以尝试强制 as.Date
这将删除时间信息,如下所示:
as.numeric(as.POSIXct(as.Date(x2))) |>
as.POSIXct(origin=as.POSIXct('1970-01-01', tz='UTC'), tz='UTC')
# [1] "2016-05-07 UTC" "2014-07-22 UTC" "2018-12-02 UTC" "2020-01-11 UTC"
# [5] NA "2019-08-15 UTC" NA NA
# [9] "2016-07-23 UTC"
当然也见this great answer。
注:
R.version.string
# [1] "R version 4.1.2 (2021-11-01)"
数据:
x1 <- structure(c(1242950400, 810950400, 827280000, NA, 1127606400,
1103068800, NA, NA, 864950400), class = c("POSIXct", "POSIXt"
), tzone = "UTC")
x2 <- structure(c(1462611420, 1406055660, 1543752840, 1578749220, NA,
1565861460, NA, NA, 1469232000), class = c("POSIXct", "POSIXt"
), tzone = "UTC")
我正在尝试读取包含一些日期变量的 excel 文件。但是当我使用该函数读取文件并显示变量时,我的两个变量的格式不同,如下例所示。
date1
[1] "2009-05-22 UTC" "1995-09-13 UTC" "1996-03-20 UTC" "2006-17-05 UTC" "2005-09-25 UTC" "2004-12-15 UTC" NA NA "1997-05-30 UTC"
date2
[1] "2016-05-07 08:57:00 UTC" "2014-07-22 19:01:00 UTC" "2018-12-02 12:14:00 UTC" "2020-01-11 13:27:00 UTC" "2013-14-21 11:40:00 UTC"
[6] "2019-08-15 09:31:00 UTC" NA NA "2016-07-23 00:00:00 UTC"
如何将 date2 的格式转换为 date1 的格式
您可以尝试强制 as.Date
这将删除时间信息,如下所示:
as.numeric(as.POSIXct(as.Date(x2))) |>
as.POSIXct(origin=as.POSIXct('1970-01-01', tz='UTC'), tz='UTC')
# [1] "2016-05-07 UTC" "2014-07-22 UTC" "2018-12-02 UTC" "2020-01-11 UTC"
# [5] NA "2019-08-15 UTC" NA NA
# [9] "2016-07-23 UTC"
当然也见this great answer。
注:
R.version.string
# [1] "R version 4.1.2 (2021-11-01)"
数据:
x1 <- structure(c(1242950400, 810950400, 827280000, NA, 1127606400,
1103068800, NA, NA, 864950400), class = c("POSIXct", "POSIXt"
), tzone = "UTC")
x2 <- structure(c(1462611420, 1406055660, 1543752840, 1578749220, NA,
1565861460, NA, NA, 1469232000), class = c("POSIXct", "POSIXt"
), tzone = "UTC")