将海军 sunset/sunrise 数据转换为时间

Converting Navy sunset/sunrise data into time

我已经从海军下载了 2015-2017 sunset/sunrise 数据,我正在尝试将其格式化为日期和时间,以便进一步与我拥有的其他数据一起使用。这就是我的数据集在 R 中的样子。

我已经设法将日期转换为正确的 R 数据格式。然而,我仍然无法将我的 rise/set 列数据从 number/integer 格式转换为时间数据(如 hh:mm)。
基于一个互联网资源,我编写了以下代码:

Sun2015$Srise<- format(strptime(Sun2015$Rise, format="%H:%M")) 

但是这在我的数据中给出了 NA

Sun2015$Srise<-str_pad(Sun2015$Rise, 4, pad="0")

Sun2015$Srise<-hour(hm(Sun2015$Srise))

然而,我收到以下错误:

Warning message: In .parse_hms(..., order = "HM", quiet = quiet) :
Some strings failed to parse.

是否有更好的方法将列转换为正确的时间格式,以便我可以将日期和时间列合并为日落和日出的日期时间列? 预先感谢您的帮助。

您可以使用 sprint("%04d", data) 将您的军事时间转换为 2400 时间字符串,然后从那里开始。例如,数据的前 5 行:

# Sample of your data
Day <- c("1/1/2015", "1/2/2015", "1/3/2015", "1/4/2015", "1/5/2015")
Rise <- c(652,652,652,653,653)
Set <- c(1755,1756,1756,1757,1757)

sun2015 <- data.frame(Day, Rise, Set)

# Convert to 2400 style strings with leading zeroes where necessary
sun2015$Rise <- sprintf("%04d", sun2015$Rise)
sun2015$Set <- sprintf("%04d", sun2015$Set)

# Merge with your date
sun2015$day_rise <- as.POSIXct(paste0(sun2015$Day, " ",sun2015$Rise), format = "%m/%d/%Y %H%M", origin = "1970-01-01", tz = "UTC")
sun2015$day_set <- as.POSIXct(paste0(sun2015$Day, " ",sun2015$Set), format = "%m/%d/%Y %H%M", origin = "1970-01-01", tz = "UTC")

> sun2015$day_rise
[1] "2015-01-01 06:52:00 UTC" "2015-01-02 06:52:00 UTC" "2015-01-03 06:52:00 UTC" "2015-01-04 06:53:00 UTC"
[5] "2015-01-05 06:53:00 UTC"
> sun2015$day_set
[1] "2015-01-01 17:55:00 UTC" "2015-01-02 17:56:00 UTC" "2015-01-03 17:56:00 UTC" "2015-01-04 17:57:00 UTC"
[5] "2015-01-05 17:57:00 UTC"

如有必要,您可以调整到合适的时区。