1

I'm writting a Python script that will look for newly created features and update them. This script will be automated to run every day at the end of the day. I'm using the Select by attribute tool to select features created on or before now (variable). I'm using UTC time zone because the "Create Date" field was created by the Enable Editor Tracking tool and by default the date is in UTC time zone.

import arcpy, datetime
from datetime import timezone

Now = datetime.datetime.now(timezone.utc)     
arcpy.SelectLayerByAttribute_management(LayerName, "New_Selection", "CreateDate <= Now")

I'm getting an invalid expression error

arcgisscripting.ExecuteError: ERROR 000358: Invalid expression
Failed to execute (SelectLayerByAttribute).

How do I use the variable Now in the expression?

1
  • Your syntax is incorrect, read the help file on how to query dates, more information here.
    – Hornbydd
    Commented May 26, 2021 at 16:39

1 Answer 1

4

Try using datetime with strftime:

import datetime as dt
import arcpy

fc = r'C:\data.gdb\featureclass'
date_field = 'CreateDate'

LayerName = 'layer123'
arcpy.MakeFeatureLayer_management(fc, LayerName)

today = dt.datetime.now().strftime(format='%Y-%m-%d') #'2021-05-26'
where = "{0} = date '{1}'".format(arcpy.AddFieldDelimiters(datasource=fc, field=date_field), today) #https://desktop.arcgis.com/en/arcmap/10.3/map/working-with-layers/sql-reference-for-query-expressions-used-in-arcgis.htm#GUID-85C03D85-F4A5-48FC-8E8C-3F79919430DB
arcpy.SelectLayerByAttribute_management(in_layer_or_view=LayerName, where_clause=where)

I'm not sure if you need to add 00:00:00 after the date:

where = "{0} = date '{1} 00:00:00'".format(arcpy.AddFieldDelimiters(datasource=fc, field=date_field), today)

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.