if Statement Between Dates?

588
2
Jump to solution
02-22-2019 09:41 AM
by Anonymous User
Not applicable

I want to update an attribute if the date from another attribute is tomorrows date. My script runs without error but nothing gets updated. I think the If statement needs to be adjusted. Any help?

with arcpy.da.UpdateCursor(layer,['StartDate','Status']) as cursor:
    for row in cursor:
        today = datetime.datetime.today()
        tomorrow = today + datetime.timedelta(1)
        tmw = datetime.datetime.strftime(tomorrow, '%Y-%m-%d 00:00:00')
        tmw2 = datetime.datetime.strftime(tomorrow, '%Y-%m-%d 23:59:59')
        com = "BETWEEN timestamp '" + tmw + "' AND timestamp '" + tmw2 +"'"
        if (str(row[0]) == com):
            print ("Match Found!")
            row[1] = 'Active'
            cursor.updateRow(row)

print ('Complete')‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
1 Solution

Accepted Solutions
KevinDunlop
Occasional Contributor III

What you script is doing is comparing the value with the where clause.  To the computer it looks something like this.

If ('2/23/2019' ==  "BETWEEN timestamp '2/23/2019 00:00:00' AND timestamp '2/23/2019 23:59:59')

   do this

This doesn't make much sense.  You need to rewrite your if state to use > and < signs.  You also need to use the date object or convert it to an integer to work since string won't compare correctly.

If ('2/23/2019' < '2/23/2019 00:00:00' AND '2/23/2019' > '2/23/2019 23:59:59')

   do this

View solution in original post

2 Replies
KevinDunlop
Occasional Contributor III

What you script is doing is comparing the value with the where clause.  To the computer it looks something like this.

If ('2/23/2019' ==  "BETWEEN timestamp '2/23/2019 00:00:00' AND timestamp '2/23/2019 23:59:59')

   do this

This doesn't make much sense.  You need to rewrite your if state to use > and < signs.  You also need to use the date object or convert it to an integer to work since string won't compare correctly.

If ('2/23/2019' < '2/23/2019 00:00:00' AND '2/23/2019' > '2/23/2019 23:59:59')

   do this

JoshuaBixby
MVP Esteemed Contributor

Your com expression is being constructed as SQL, but you aren't applying it as SQL.  Try

today = datetime.datetime.today()
tomorrow = today + datetime.timedelta(1)

tmw = datetime.datetime.strftime(tomorrow, '%Y-%m-%d 00:00:00')
tmw2 = datetime.datetime.strftime(tomorrow, '%Y-%m-%d 23:59:59')
com = "BETWEEN timestamp '" + tmw + "' AND timestamp '" + tmw2 +"'"

with arcpy.da.UpdateCursor(layer,['StartDate','Status'], 'StartDate ' + com) as cursor:
    for row in cursor:
        row[1] = 'Active'
        cursor.updateRow(row)

print ('Complete')