I'm trying to add a date field without it taking too long. Using arcpy.da.UpdateCursor took forever, so I'm trying Add field and calculate field ... which I cannot seem to get working! Any advice is appreciated! ArcGIS 2.9. Below is part of my code.
Thank you - Daniel
import arcpy, os, sys
import datetime
PatrolDateCalc = datetime.date(2022, 9, 19)
fc = oh
field = "PatrolDate"
if arcpy.ListFields(fc, field) == True:
Print ("PatrolDate" + fc + "field already present")
else:
arcpy.management.AddField(fc, field, "DATE", "10", "", "", "Patrol Date", "", "NON_REQUIRED")
arcpy.management.CalculateField(fc, field, PatrolDateCalc, "PYTHON3", "", "DATE", "NO_ENFORCE_DOMAINS")
fc = ug
field = "PatrolDate"
if arcpy.ListFields(fc, field) == True:
Print ("PatrolDate" + fc + "field already present")
else:
arcpy.management.AddField(fc, field, "DATE", "10", "", "", "Patrol Date", "", "NON_REQUIRED")
arcpy.management.CalculateField(fc, field, PatrolDateCalc, "PYTHON3", "", "DATE", "NO_ENFORCE_DOMAINS")
In [14]:
Line: arcpy.management.CalculateField(fc, field, PatrolDateCalc, "PYTHON3", "", "DATE", "NO_ENFORCE_DOMAINS")
File C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\management.py, in CalculateField:
Line 5588: raise e
File C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\management.py, in CalculateField:
Line 5585: retval = convertArcObjectToPythonObject(gp.CalculateField_management(*gp_fixargs((in_table, field, expression, expression_type, code_block, field_type, enforce_domains), True)))
File C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing\_base.py, in <lambda>:
Line 512: return lambda *args: val(*gp_fixargs(args, True))
ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000840: The value is not a SQL Expression.
Failed to execute (CalculateField).
Where is "PatrolDateCalc" declared? I don't see it.
Sorry about that! I forgot to include the definition here: I have updated the post to include PatrolDateCalc = datetime.date(2022, 9, 19).
I assume it is complaining about 'PatrolDateCalc', which I done see being defined anywhere.
Thank you for responding! Yep, PatrolDateCalc is defined in my code, but I forgot to put it here. I've updated the post to include PatrolDateCalc = datetime.date(2022, 9, 19).
Try using PatrolDateCalc = datetime.datetime(2022, 9, 19)
I don't often use the arcpy version of CalculateField, but I have three thoughts and ideas:
Let us know and good luck!
Here is what worked for me on a file geodatabase on a field declared with the Date type:
arcpy.management.CalculateField(myLayer, myField, "'{0}'".format(PatrolDateCalc.strftime("%m/%d/%Y")))
Note that you may want (or even need) to change the parameter to strftime to match your locale better. I don't know.
Let us know and good luck!