将 ISO 8601 标准时间戳强制转换为 Date 类
时间戳已经在ISO 8601 standard format 中,这是明确的。因此,转成Date类时需要格式规范:
as.Date(recfive$timestamp)
#> [1] "2018-01-27" "2018-01-27" "2018-01-27" "2018-01-27" "2018-01-27"
将 ISO 8601 标准时间戳强制转换为 POSIXct 类(日期时间)
强制转换为日期时间对象(POSIXct 类)时,必须指定时区。虽然,时区已在输入数据中由尾随字母 Z 指示(如 Zulu = UTC),但遗憾的是,这在输入时被忽略了。
在我当前的语言环境中,使用本地时区创建一个 POSIXct 对象,其中时间戳表示与指定时间不同的实例(在冬季,CET 比 UTC 早一小时)。
as.POSIXct(recfive$timestamp)
#> [1] "2018-01-27 CET" "2018-01-27 CET" "2018-01-27 CET" "2018-01-27 CET" "2018-01-27 CET"
因此,必须明确指定时区:
as.POSIXct(recfive$timestamp, tz = "UTC")
#> [1] "2018-01-27 UTC" "2018-01-27 UTC" "2018-01-27 UTC" "2018-01-27 UTC" "2018-01-27 UTC"
请注意,as.POSIXct() 已返回一个截断的日期时间,表示一天的开始。
要获取指定的完整日期时间,可以使用格式规范调用as.POSIXct():
as.POSIXct(recfive$timestamp, format = "%FT%TZ", tz = "UTC")
#> [1] "2018-01-27 09:01:49 UTC" "2018-01-27 00:04:08 UTC" "2018-01-27 09:04:22 UTC"
#> [4] "2018-01-27 09:04:28 UTC" "2018-01-27 00:07:38 UTC"
另外,有许多包专门用于将日期时间字符串简化或快速强制转换为 POSIXct 类,它们都返回相同的结果:
lubridate::ymd_hms(recfive$timestamp)
anytime::anytime(recfive$timestamp, asUTC = TRUE)
anytime::utctime(recfive$timestamp, tz = "UTC")
fasttime::fastPOSIXct(recfive$timestamp, tz = "UTC")
数据
recfive <- data.table::fread(
"timestamp
2018-01-27T09:01:49Z
2018-01-27T00:04:08Z
2018-01-27T09:04:22Z
2018-01-27T09:04:28Z
2018-01-27T00:07:38Z")