如何解决无法从shapefile中的日期属性中提取季节
app.root
esri中的Popup
的数据类型为date,但是当我在python控制台中将其打印出来时,显然是str。我正在尝试使用python根据指定的日期范围填写“季节”字段。这是我到目前为止的内容:
FID REPORT_DAT Season
0 8/23/2018
1 9/23/2020
2 1/23/2020
我的打印声明打印出来:
REPORT_DAT
我以为我已将日期转换为上面正确的格式,并将其传递到 import arcpy
from datetime import date,datetime
arcpy.env.overwriteOutput = True
fc = r"C:\Users\RoadKill.shp"
#arcpy.AddField_management("roadkill","Season","TEXT","","20")
seasons = {'spring':(datetime(2020,03,30),datetime(2020,04,13)),'summer':(datetime(2020,14),10,31)),'autumn':(datetime(2020,11,01),17)),'winter':(datetime(2018,17),datetime(2019,29))}
rows = arcpy.SearchCursor(fc)
for row in rows:
datetimeVal = row.getValue("REPORT_DAT")
formattedTime = datetime.strftime(datetimeVal,"%Y/%m/%d")
datetime = datetime.strptime(formattedTime,"%Y/%m/%d").date()
print(datetime,type(datetime))
def get_season(datetime):
print(datetime,type(datetime))
for season,(season_start,season_end) in seasons.items():
if datetime>=season_start and datetime<= season_end:
return season
arcpy.CalculateField_management("roadkill",get_season("REPORT_DAT"),"PYTHON_9.3","")
字段,但仍然出现此错误:
(datetime.date(2018,8,23),<type 'datetime.date'>)
('REPORT_DAT',<type 'str'>)
关于如何正确转换我的日期字段的任何建议?
解决方法
您必须先转换日期,然后再进行比较。您可以尝试以下方法:
# First harmonize your seasons dates by replacing date by datetime
seasons = {'spring':(datetime(2020,03,30),datetime(2020,04,13)),'summer':(datetime(2020,14),10,31)),'autumn':(datetime(2020,11,01),17)),'winter':(datetime(2020,17),29))}
def date_conversion(my_date):
values = my_date.split('/')
year,month,day = int(values[0]),int(values[1]),int(values[2])
return datetime(year,day)
# rename the variable date by my_date
def get_season(my_date):
my_date = date_conversion(my_date)
for season,(season_start,season_end) in seasons.items():
# Refine your comparison
if season_start <= my_date <= season_end:
# You should return season,not seasons
return season
,
我最终使用了更新游标来解决我的问题。
with arcpy.da.UpdateCursor(fc,fields) as cursor:
for row in cursor:
myDate = datetime.strptime(datetime.strftime(row[0],"%m/%d/%Y"),"%m/%d/%Y")
if (myDate >= datetime.strptime("03/30/2020","%m/%d/%Y") and myDate <= datetime.strptime("04/13/2020","%m/%d/%Y")):
row[1] = "SPRING"
elif (myDate >= datetime.strptime("04/14/2020","%m/%d/%Y")and myDate <= datetime.strptime("10/31/2020","%m/%d/%Y")):
row[1] = "SUMMER"
elif (myDate >= datetime.strptime("02/06/2020","%m/%d/%Y") and myDate <= datetime.strptime("01/10/2020","%m/%d/%Y")):
row[1] = "FALL"
elif (myDate >= datetime.strptime("02/10/2020","%m/%d/%Y")):
row[1] = "WINTER"
cursor.updateRow(row)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。