ArcGIS中用Python生成2019-2020逐小时日期字段的技术咨询
前置准备
- 在目标属性表中新建所需字段:如果仅需导出展示符合指定格式的时间,可新建文本型字段;如果后续要开展时间筛选、时空分析,建议同步新建日期型字段,计算效率更高
- 确认属性表的记录顺序为严格按照逐小时采集顺序从早到晚排列,无乱序、无错位
可落地方案
方案1:字段计算工具快速实现(适合单表小批量数据)
操作路径:打开目标图层属性表 → 右键新建的字段 → 选择「计算字段」→ 解析语言选择Python
在代码块中输入如下脚本:
import datetime # 固定时间起点:2019年1月1日0点 start_time = datetime.datetime(2019, 1, 1, 0, 0, 0) # 行计数器,从第0行开始累加 row_counter = 0 def generate_timestamp(): global row_counter current_time = start_time + datetime.timedelta(hours=row_counter) # 按要求生成AM/PM标识:0-11小时标注AM,12-23小时标注PM time_period = "AM" if current_time.hour < 12 else "PM" # 匹配指定格式:日/月/年 时:分:秒 时段,无月份、日期的前导零 formatted_str = f"{current_time.day}/{current_time.month}/{current_time.year} {current_time.hour:02d}:{current_time.minute:02d}:{current_time.second:02d} {time_period}" row_counter += 1 return formatted_str
在表达式输入框中填写generate_timestamp(),点击确定即可逐行填充对应时间。
注意:如果计算过程中中断,需清空当前字段的所有内容后重新执行计算,避免计数器错位导致时间序列偏移。当总记录数与要求的时间点总数匹配时,最后一行生成的时间恰好为
31/12/2020 23:00:00 PM。
方案2:独立ArcPy脚本实现(适合大数据量、可复用场景)
如果数据量较大,可直接通过ArcPy脚本批量遍历游标完成填充,避免字段计算的卡顿问题:
import arcpy import datetime # 替换为实际的数据集路径 dataset_path = r"C:\你的本地数据路径\卫星数据.gdb\逐小时观测数据" # 替换为实际新建的时间字段名 time_field_name = "obs_time_str" # 定义固定时间范围 start_time = datetime.datetime(2019, 1, 1, 0, 0, 0) end_time = datetime.datetime(2020, 12, 31, 23, 0, 0) # 计算时间范围对应的总记录数 total_time_points = int((end_time - start_time).total_seconds() / 3600) + 1 # 提前校验记录数是否匹配 actual_record_count = int(arcpy.GetCount_management(dataset_path)[0]) if actual_record_count != total_time_points: raise ValueError(f"记录数不匹配:当前数据集共{actual_record_count}条记录,匹配目标时间范围需要{total_time_points}条记录,请检查数据顺序或范围") # 逐行填充时间值 with arcpy.da.UpdateCursor(dataset_path, [time_field_name]) as cursor: for row_index, row in enumerate(cursor): current_time = start_time + datetime.timedelta(hours=row_index) time_period = "AM" if current_time.hour < 12 else "PM" formatted_str = f"{current_time.day}/{current_time.month}/{current_time.year} {current_time.hour:02d}:{current_time.minute:02d}:{current_time.second:02d} {time_period}" row[0] = formatted_str cursor.updateRow(row) print("时间序列填充完成,最终记录的时间为31/12/2020 23:00:00 PM")
注意事项
- 脚本生成的日期格式严格按照
日/月/年的顺序匹配需求,没有使用常规的月/日/年格式,避免导出时出现时间错位 - 若需要在ArcGIS中直接按时间查询、做时空立方体分析,可在脚本中同步新建日期型字段,直接将
current_time对象赋值给日期字段,无需做字符串转换,运算效率远高于文本型字段 - 整个时间序列的总长度为17544个小时,对应2019-2020年全部逐小时时间点,无遗漏
内容的提问来源于stack exchange,提问作者Andrea H.
相关产品推荐
相关产品推荐

