1

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

3
  1. 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
  2. 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.
  3. There is a chance that having the local variable getsecond be named the same as the function getsecond is causing problems.
  4. Python field names should be surrounded by ! in Calculate Field.
  5. 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
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.