Field Calculator in Python using Dates

2149
2
02-03-2012 12:54 PM
MichalisAvraam
New Contributor III
I have a field in my shapefile that is of type "Date".

I want to figure out the difference between that "Date" and today, in weeks.

My assumption was that (datetime.date() - !Date!) would produce a timedelta object, which i would simply call to find out the difference. Hence my code below:

(datetime.date.today() - !Date!).days / 7


Of course, that says it is a syntax error, which doesn't explain much. Any pointers to manipulating dates in the field calculator?
Tags (2)
0 Kudos
2 Replies
DarrenWiens2
MVP Honored Contributor
I don't know off the top of my head how to do it in Python, but in VBScript you should be able to use the example on this help page (and divide by 7).
0 Kudos
MichalisAvraam
New Contributor III
I don't know off the top of my head how to do it in Python, but in VBScript you should be able to use the example on this help page (and divide by 7).


Thanks.

I finally got it to work, after realizing that when you use !Date! in the field calculator, it actually returns a string rather than a datetime.date() object.

In my pre-processor I had the following:

[PHP]
firstTime = datetime.date(2009, 7, 16)
def timeDif(a):
    month, date, year = a.split('/')
    featDate = datetime.date(int(year), int(month), int(date))
    timeDiff = featDate - firstTime
    return timeDiff.days / 7
[/PHP]

and in my new field I simply had:

[PHP]
timeDif(!Date!)
[/PHP]

Frustrating to figure it out, but hey, it works now.