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

ArcGIS Pro下载含date_time的REST数据:保留时间信息方法咨询

问题

在ArcGIS Pro中通过Python调用自定义几何下载ArcGIS REST服务数据,已实现保存为shapefile,但date_time字段仅保留日期部分。已知shapefile不支持存储完整datetime,尝试保存至gdb因操作复杂受阻(新手),咨询以下问题:

  1. 是否有简便方法将数据保存至gdb并保留date_time?
  2. 能否修改查询以拆分出单独的date和time列?
  3. 能否将date_time以字符串形式返回,以便手动转换为日期和时间?

原代码如下:

from arcgis.gis import GIS
from arcgis.features import FeatureLayer
from arcgis.geometry.filters import intersects

gis = GIS("pro")

#The ESRI JSON used to subset the REST data
geometry = {
  "spatialReference": {"wkid": 4326},
  "rings": [
    [
      ["-124.785944", "49.142568"],
      ["-125.439631", "50.001049"],
      ["-124.928766", "50.335311"],
      ["-123.735655", "49.654732"],
      ["-124.404157", "49.265739"],
      ["-124.785944", "49.142568"]
    ]
  ]
}

# The REST service URL
rest_service_url = "https://gisp.dfo-mpo.gc.ca/arcgis/rest/services/FGP/MSDI_Dynamic_Current_Layer/MapServer/0"

# Access the feature layer using the REST service URL
layer = FeatureLayer(rest_service_url)

# Query the feature layer
features = layer.query(where="1=1", geometry_filter=intersects(geometry, 4326))

print(f"Number of features found: {len(features.features)}")

# Save to local Dir
output_dir = r"C:\Users\name\Documents\"  

# Save features to shp
features.save(output_dir, "currents.shp")

解答

1. 简便保存至gdb并保留datetime

直接修改features.save()的参数,将输出路径指向文件地理数据库(File Geodatabase)即可,无需复杂操作。如果目标gdb不存在,save方法会自动创建:

# 替换原保存shp的代码
output_gdb = r"C:\Users\name\Documents\my_data.gdb"
features.save(output_gdb, "currents")

File Geodatabase原生支持datetime类型,保存后的要素类会完整保留date_time字段的日期和时间信息。

2. 查询时拆分date和time列

在query方法的out_fields参数中使用ArcGIS REST支持的SQL函数,直接从datetime字段拆分出日期、时间单独列。假设原datetime字段名为date_time,修改查询代码如下:

# 指定输出字段,新增拆分后的日期、时间列
fields = [
    "OBJECTID",
    "date_time",
    "CAST(date_time AS DATE) AS date_only",
    "CAST(date_time AS TIME) AS time_only"
    # 加入你需要的其他业务字段
]

features = layer.query(
    where="1=1",
    geometry_filter=intersects(geometry, 4326),
    out_fields=fields
)

查询返回的要素会新增date_only(仅日期)和time_only(仅时间)字段,后续保存为shp或gdb都能正常保留这两个字段。

3. 将datetime转为字符串返回

使用TO_CHAR函数(ArcGIS REST支持的SQL函数),在查询时将datetime字段格式化为字符串:

# 自定义字符串格式,示例为'年-月-日 时:分:秒'
fields = [
    "OBJECTID",
    "TO_CHAR(date_time, 'YYYY-MM-DD HH24:MI:SS') AS date_time_str"
    # 加入你需要的其他业务字段
]

features = layer.query(
    where="1=1",
    geometry_filter=intersects(geometry, 4326),
    out_fields=fields
)

返回的date_time_str是完整日期时间格式的字符串,可通过Python的datetime模块手动转换为日期时间对象:

from datetime import datetime

for feat in features.features:
    dt_str = feat.attributes["date_time_str"]
    dt_obj = datetime.strptime(dt_str, "%Y-%m-%d %H:%M:%S")
    # 可将转换后的对象存回属性或做后续处理
    feat.attributes["converted_datetime"] = dt_obj

内容的提问来源于stack exchange,提问作者seak23

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:07:33