R将日期和小时转换为时间_stamp只生成1天中1小时的NA



我正在尝试使用as.POSIXct.生成一个小时的时间戳,即0,1,2-23和一个日期

由于.POSIXct在3月29日第1小时生成NA,它在2020年2月至12月的所有其他日期都能正常工作。此外,29日的00点出现在格林尼治标准时间,而不是像其他时间一样出现在英国夏令时。

下面的代码为我生成了问题,strptime创建的日期有差异——不起作用的日期在GMT,另一个在BST——不确定这将如何导致1小时的NA?

#create date combining characters from input file only difference is the 29
#all other dates work as expect using the 30 for example
date_working <- strptime(paste("30","March","2020",sep = "-"), "%d-%B-%Y")
date_not_working <- strptime(paste("29","March","2020",sep = "-"), "%d-%B-%Y")
#hour characters are the same for both NA is only generated for hour "1"
hour <- c("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", 
"12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", 
"23")
#Use paste to combine hour, day, month, year with right seperators to get date format for as.POSIXct
time_stamp_working <- as.POSIXct(paste(date_working,paste(hour,"00",sep = ":"),sep = " "), 
format = "%Y-%m-%d %H:%M")
#Use paste to combine hour, day, month, year with right seperators to get date format for as.POSIXct
time_stamp_not_working <- as.POSIXct(paste(date_not_working,paste(hour,"00",sep = ":"),sep = " "), 
format = "%Y-%m-%d %H:%M")

以下输出显示问题

> time_stamp_working[1:5]
[1] "2020-03-30 00:00:00 BST" "2020-03-30 01:00:00 BST" "2020-03-30 02:00:00 BST"
[4] "2020-03-30 03:00:00 BST" "2020-03-30 04:00:00 BST"
> time_stamp_not_working[1:5]
[1] "2020-03-29 00:00:00 GMT" NA                        "2020-03-29 02:00:00 BST"
[4] "2020-03-29 03:00:00 BST" "2020-03-29 04:00:00 BST"

正如@Allan Cameron所解释的,夏令时适用于当地时区。不过,如果您停留在GMT/UTC时区,这个问题是可以避免的。

as.POSIXct(paste(date_not_working,paste(hour,"00",sep = ":"),sep = " "), 
format = "%Y-%m-%d %H:%M", tz = 'GMT')
# [1] "2020-03-29 00:00:00 GMT" "2020-03-29 01:00:00 GMT" "2020-03-29 02:00:00 GMT"
# [4] "2020-03-29 03:00:00 GMT" "2020-03-29 04:00:00 GMT" "2020-03-29 05:00:00 GMT"
# [7] "2020-03-29 06:00:00 GMT" "2020-03-29 07:00:00 GMT" "2020-03-29 08:00:00 GMT"
#[10] "2020-03-29 09:00:00 GMT" "2020-03-29 10:00:00 GMT" "2020-03-29 11:00:00 GMT"
#[13] "2020-03-29 12:00:00 GMT" "2020-03-29 13:00:00 GMT" "2020-03-29 14:00:00 GMT"
#[16] "2020-03-29 15:00:00 GMT" "2020-03-29 16:00:00 GMT" "2020-03-29 17:00:00 GMT"
#[19] "2020-03-29 18:00:00 GMT" "2020-03-29 19:00:00 GMT" "2020-03-29 20:00:00 GMT"
#[22] "2020-03-29 21:00:00 GMT" "2020-03-29 22:00:00 GMT" "2020-03-29 23:00:00 GMT"

相关内容

  • 没有找到相关文章

最新更新