You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言根据指定年份生成逐小时完整日期序列及缺失值处理方法

给定目标年份生成逐小时完整日期时间序列的实现方法

以下是不同常用工具的实现方案,可直接适配闰年/非闰年,自动计算总时长:

Python 实现(基于pandas)

import pandas as pd

# 填入目标年份
target_years = [2017, 2018]
hourly_series = pd.Series(dtype='datetime64[ns]')

for year in target_years:
    # 左闭右开逻辑自动过滤下一年首日0点,无需单独计算天数
    year_series = pd.date_range(
        start=f'{year}-01-01 00:00:00', 
        end=f'{year+1}-01-01 00:00:00',
        freq='H', 
        inclusive='left'
    )
    hourly_series = pd.concat([hourly_series, pd.Series(year_series)])

# 输出验证:2个非闰年总长度为17520
print(f"总记录数:{len(hourly_series)}")
print("前十条记录:\n", hourly_series.head(10))

R 语言实现(基于lubridate)

library(lubridate)

# 填入目标年份
target_years <- c(2017,2018)
hourly_series <- c()

for (y in target_years) {
  start_time <- ymd_hms(paste0(y, "-01-01 00:00:00"))
  end_time <- ymd_hms(paste0(y+1, "-01-01 00:00:00")) - hours(1)
  year_series <- seq(from = start_time, to = end_time, by = "hour")
  hourly_series <- c(hourly_series, year_series)
}

# 输出验证
print(paste0("总记录数:", length(hourly_series)))
print("前十条记录:")
head(hourly_series, 10)

注意事项

  • 无需手动判断闰年,时间工具库会自动匹配当年总小时数,闰年自动生成8784条记录
  • 若需要指定时区避免夏令时偏差,可在生成序列时补充对应时区参数即可
  • 若需要输出YYYY-MM-DD HH:MM:SS格式的字符串,调用对应时间库的格式化方法转换即可

内容的提问来源于stack exchange,提问作者Sang won kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:45:02