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

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Aug 28, 2019 at 15:01

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
answered Aug 28, 2019 at 16:16
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
PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
answered Aug 28, 2019 at 18:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.