I am trying to use a search cursor to look up a date field to only return LastUpdates within the last 30 days.
today = datetime.date.today()
I want to use the datetime and date field types which are in different formats and is why I can't calculate the difference.
How can I format them the same to accomplish this ?
Solved! Go to Solution.
I am confused on line 9
dt_i = cur.fields.index(dt_fld)
Where did you get index from ?
The fields property for a cursor returns a list, which has an index method.
I modified slightly on just the variable names but get the error.
ValueError: tuple.index(x): x not in tuple
with arcpy.da.SearchCursor(fc1, datefield) as cur:
dt_i = cur.fields.index(datefield)
dt_filtered = (rec for rec in cur
if rec[dt_i] and datetime.now() - rec[dt_i] <= timedelta(30))
for row in dt_filtered:
print ("{0}".format(row[0]))
I really need to see the whole code block since you are defining variables upstream.
The error message itself is saying that datefield is not present in the fields from the cursor, which does seem odd given that is the only field you passed. Maybe it is a case mismatch, I am not sure.
Provide more code and also put a print statement in for datefield and even cur.fields.
import arcpy
import datetime
from datetime import timedelta
# Set Feature Variables
fc1 = r'Database Connections\a.sde\BACK.wNetwork\BACK.wSystemValve'
datefield = ['LASTUPDATE']
with arcpy.da.SearchCursor(fc1, datefield) as cur:
dt_i = cur.fields.index(datefield)
dt_filtered = (rec for rec in cur
if rec[dt_i] and datetime.now() - rec[dt_i] <= timedelta(30))
for row in dt_filtered:
print ("{0}".format(row[0]))
Your welcome,
However, this doesn't work though, I need to work out the error still.
datefield can be a list in line 9, but not in line 10. Try:
datefield = ['LASTUPDATE'] # list
with arcpy.da.SearchCursor(fc1, datefield) as cur:
dt_i = cur.fields.index(datefield[0]) # first element in list
# or - as in Joshua's original code
datefield = ['LASTUPDATE']
dt_fld = 'LASTUPDATE'
with arcpy.da.SearchCursor(fc1, datefield) as cur:
dt_i = cur.fields.index(dt_fld)
Thanks for the advice.
I still have the following issue.
TypeError: unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'
That is probably related to how you are importing the datetime modules.
# insead of
import datetime
if rec[dt_i] and datetime.datetime.now() - rec[dt_i] <= datetime.timedelta(30))
# use this
from datetime import datetime, timedelta
if rec[dt_i] and datetime.now() - rec[dt_i] <= timedelta(30))
The second method of importing modules will save some typing and make the code easier to read, as illustrated in lines 5 and 11 above.
Perfect, that was my issue in how I had redundant importing of these date -time modules.
It works now.