Using CalculateField to update field with date

只愿长相守 提交于 2019-12-12 14:18:17

问题


I'm working with Arcpy in ArcGIS and trying to write code that will update a field with the last day of the previous month (ie. if I run the code today, 2017-09-01, it will update the field with 2017-08-31).

If I do a manual field calculation, I can get it to work using VBScript and the pre-logic script code:

Dim FC
FC = DateSerial(Year(Date), Month(Date), 0)

and then setting the field to equal FC:

I've tried to integrate this into code so it can be set to run automatically, but haven't had any luck. Is anyone able to identify where I'm going wrong with the below code?

import arcpy

inTable = r'C:\1 Block Watch Cr\Base_Data.gdb\Districts'
field = "Final_Date"
exp = 'getdate()'
codeblock = '''def getdate():
    DateSerial(Year(Date ()), Month(Date ()), 0)'''

arcpy.CalculateField_management(inTable, field, exp, "VB", codeblock)

I am getting the following error message:


回答1:


You are getting the error "Cannot use parenthesis while calling the sub". This is because of the following rules of a function call in VBScript:

3 Methods of calling a function in VBScript:

  • fn a,b - when using this way, you CANNOT enclose the parameter-list in the parenthesis
  • Call fn(a,b) - when you write the call keyword explicitly, you must enclose the parameter-list in parenthesis
  • c=fn(a,b) - when you assign the value returned by the function to a variable, you must enclose the parameter-list in the Parenthesis.

To understand better about these rules, check this answer.

What happened in your case:

In the VBScript code that you posted, you used the 3rd method and you followed the rule by enclosing the parameter-list inside parenthesis. Hence, it worked fine.

In the Python code, you are simply using DateSerial(Year(Date ()), Month(Date ()), 0) which is the 1st method. According to the rule of 1st method, you must not enclose the parameter-list in the parenthesis. Since you did enclose the param-list inside parenthesis, you violated that rule and got that error.

Probable Solution:

Either use the call method 1 correctly by removing the parenthesis as below:

codeblock = '''def getdate():
    DateSerial Year(Date ()), Month(Date ()), 0'''

OR explicitly write the call keyword before actually calling the function:

codeblock = '''def getdate():
    Call DateSerial(Year(Date ()), Month(Date ()), 0)'''

OR try storing the resulting date in a variable as below:

codeblock = '''def getdate():
    varDate = DateSerial(Year(Date ()), Month(Date ()), 0)'''

Please note that I do not know python. So, I am assuming whatever python code you have written is correct. This error was specific to vbScript, hence wrote this answer.



来源:https://stackoverflow.com/questions/46061886/using-calculatefield-to-update-field-with-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!