I am using Python 2.7 in calculate value in ModelBuilder. I want to query both 30 seconds before and after the variable. The original value keeps returning not the time change. What am I not defining?
Expression ("%Da%")
Code Block:
def getsecond():
from datetime import datetime
getsecond == ("%Da%")+ timedelta(seconds=30)
return getsecond
type string
The variable Da is a date field
2 Answers 2
- Despite being a date field, the "Da" field would be treated as unicode within the Field Calculator. You may need to first convert the field value to datetime format, as described here: https://stackoverflow.com/questions/22219210/convert-the-unicode-to-datetime-format?rq=1
- While you have defined a function, you are not calling it, and the function itself has no way of knowing what the field value is.
- There is a chance that having the local variable getsecond be named the same as the function getsecond is causing problems.
- Python field names should be surrounded by
!
in Calculate Field. - You have an operand that would return True/False (
==
) not a new calculated value (=
)
Some suggestions:
Change Expression to updateSecond(!Da!)
Change Code Block to:
from datetime import datetime
def updateSecond(datefield):
getsecond = datefield + timedelta(seconds=30)
# May instead have to do something like the following:
# assumes field values looks like u'2014-03-06T04:38:51Z' in the example
# getsecond = datetime.strptime(datefield, '%Y-%m-%dT%H:%M:%SZ')
return getsecond
I implemented all of @smiller’s suggestions. I had to change the order of the lines so that it formatted before calling the function but the below now works.
from datetime import datetime, date, time, timedelta
def updateSecond(Da):
then = datetime.strptime(Da, '%m/%d/%Y %I:%M:%S %p')
sec = timedelta(seconds=30)
updateSecond = then + sec
# May instead have to do something like the following:
# assumes field values looks like u'2014-03-06T04:38:51Z' in the example
updateSecond = datetime.strptime(Da, '%m/%d/%Y %I:%M:%S %p')
updateSecond = then + sec
return updateSecond
Explore related questions
See similar questions with these tags.