0

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.

4
  • As per the help center please do not include chit chat like greetings and thanks in your posts.
    – PolyGeo
    Dec 7, 2021 at 23:28
  • 4
    Why did you stop using AsText? The error is straight forward, you cant "add" data objects and strings.
    – KHibma
    Dec 7, 2021 at 23:42
  • I don’t use as text because the field is a date format
    – Oliver
    Dec 8, 2021 at 4:55
  • Text is the only format in which dates can be compared.
    – Vince
    Dec 9, 2021 at 20:15

1 Answer 1

1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.