Select to view content in your preferred language

Calculate date difference

5136
5
11-19-2013 10:51 AM
ErnestoCarreras3
Regular Contributor
Hi,
I need to calculate the difference between two dates in days. I need it to work within the Model Builder since these are models that need to be published later as a GP service. I have two fields, one with the Inspection date and the other with the Current date.
Something similar to the below VBscript:

DateDiff("d", [date_field], Now())


Any advice will be appreciated. Thanks in advanced.
Tags (2)
0 Kudos
5 Replies
MattSayler
Frequent Contributor
You can do that with the 'datetime' module:
http://docs.python.org/release/2.6.8/library/datetime.html

Something like:
import datetime
date1 = "1/1/1990"
date2 = "1/1/1980"
x = datetime.datetime.strptime(date1, "%m/%d/%Y")
y = datetime.datetime.strptime(date2, "%m/%d/%Y")
z = x - y
print z.days
0 Kudos
ChrisSnyder
Honored Contributor
Not sure how to pull it off in model builder, but the Python datetime module works like this:

import datetime, arcpy
time1 = arcpy.da.SearchCursor(myFC, ["MY_DATE_FIELD"], "OBJECTID = 1").next()
time2 = datetime.datetime.now()
elapsedTime = time2 - time1
print "Total elapsed seconds: " + str(elapsedTime.totalSeconds)
print "Total elapsed days: " + str(elapsedTime.days)
0 Kudos
ChrisSnyder
Honored Contributor
Woops - jinx - had that window open too long before I hit submit!
0 Kudos
MattSayler
Frequent Contributor
Great minds. 🙂
0 Kudos
ErnestoCarreras3
Regular Contributor
Thanks to both of you!!!
0 Kudos