import arcpy, os
from datetime import datetime, timedelta
arcpy.env.overwriteOutput = True
# change path to datasource
fc = r"D:\Xander\GeoNet\MergePolsDate\Reserves_copy.shp"
fld_start = "DateFrom" # create date field and fill it with content of StartDate
fld_end = "DateTo" # create date field and fill it with content of EndDate
fld_name = "Name"
fld_outname = "OutputName" # output name
len_outname = 75
# output shape
fc_out = r"D:\Xander\GeoNet\MergePolsDate\Reserves_merged3.shp"
# create empty output shapefile
ws_path, fc_out_name = os.path.split(fc_out)
arcpy.CreateFeatureclass_management(ws_path, fc_out_name,
"POLYGON", fc, "SAME_AS_TEMPLATE", "SAME_AS_TEMPLATE", fc)
# add string field
arcpy.AddField_management(fc_out, fld_outname, "TEXT", "", "", len_outname)
flds = ("SHAPE@", fld_start, fld_end, fld_name)
flds_out = ("SHAPE@", fld_start, fld_name, fld_outname)
# create a unique list of dates from start date
lst_dates = list(set([row[0] for row in arcpy.da.SearchCursor(fc, (fld_start))]))
lst_dates.sort()
# insert cursor to store features to new featureclass
with arcpy.da.InsertCursor(fc_out, (flds_out)) as curs_out:
# loop through list of unique dates
for date in lst_dates:
# create an expression
expression = "{0} <= date '{2}' AND {1} >= date '{2}'".format(
arcpy.AddFieldDelimiters(fc, fld_start),
arcpy.AddFieldDelimiters(fc, fld_end), date)
i = 0
# create the searchcursor with the expression
with arcpy.da.SearchCursor(fc, flds, where_clause=expression) as curs:
for row in curs:
pol = row[0]
name = row[3] # take name of first polygon
if i == 0:
# first polygon is just the polygon"
polygon = pol
else:
# next polygons are added with union
polygon = polygon.union(pol)
i += 1
# insert the feature into the output featureclass
datefrom = date
i_date = lst_dates.index(date)
if i_date + 1 > len(lst_dates) - 1:
dateto = ""
outname = "{0} {1} - {2}".format(name, datefrom.strftime('%Y/%m/%d'), dateto)
else:
dateto = lst_dates[i_date + 1] - timedelta(days=1)
outname = "{0} {1} - {2}".format(name, datefrom.strftime('%Y/%m/%d'), dateto.strftime('%Y/%m/%d'))
curs_out.insertRow((polygon, row[1], name, outname))