ArcPy Date Format – SQL Expression Guide for ArcGIS Pro

arcgis-proarcpydatetimesqltypeerror

I'm trying to use definitionquery to keep entities where date is smaller or equal to a certain date ( variable entered by the user). The Variable and the field in the table are formatted as dates. when running my script the error is a concatenate error.

 Traceback (most recent call last):
  File "C:\Users\...\zoomDate.py", line 10, in <module>
    lyr.definitionQuery = '"start_date" <= ' + "'"+arcpy.GetParameter(0)+"'"
TypeError: can only concatenate str (not "datetime.datetime") to str
aprx = arcpy.mp.ArcGISProject('CURRENT')
mapx = aprx.listMaps()[0]
lyr = mapx.listLayers()[2]
Date = arcpy.GetParameter(0)

lyr.definitionQuery = '"start_date" <= ' + "'"+arcpy.GetParameter(0)+"'"
lyt = aprx.listLayouts()[0]
mf = lyt.listElements('MAPFRAME_ELEMENT')[0]

mf.camera.setExtent(mf.getLayerExtent(lyr, False, True))

I was using GetParameterAsText to run almost the same script on string variables and it work flawlessly.

Best Answer

The easiest way to get past the error you're receiving is to cast the date object to a string.

In your example, this looks like (str()):

lyr.definitionQuery = '"start_date" <= ' + "'"+str(arcpy.GetParameter(0))+"'"

start_date <= some date

However, I'll caution without knowing your actual date input, this might not work as the date format may not match your data, thus it'll never compare properly. This is almost certain to be true if your start_date is a string instead of an actual date. In this case, you'll probably want to look up how to format dates.

If you have an actual Date field, try the following syntax, noting the timestamp keyword

dateCompare = arcpy.GetParameter(0)
lyr.definitionQuery = "start_date <= timestamp '{}'".format(dateCompare)
Related Question