[GIS] Calculating field with hour from date time field with ArcPy

arcpydatetimefield-calculatorpython-parsersyntaxerror

This expression works in the field calculator to give me the hour from the datetime field called dtrepor

arcpy.time.ParseDateTimeString(!dtrepor!).strftime('%H')

But how do I call it in python?
I have tried the following:

hour = arcpy.time.ParseDateTimeString(!dtrepor!).strftime('%H')
arcpy.CalculateField_management(saved_Incidents, "mil_time", hour , "PYTHON")  

But it gives me a syntax error?

Best Answer

The easiest way to find out how to reproduce something in python is to run it once in ArcMap using the ArcToolbox tool (or in this case, the Field Calculator), and then choosing Copy Python Snippet from the geoprocessing results.

  1. Run the Field Calculator
    enter image description here

  2. Open the Results pane (Geoprocessing > Results)
    enter image description here

  3. Find the corresponding tool results, right-click and select Copy As Python Snippet
    enter image description here

  4. Now paste that Python snippet into your IDE. This will be the code you want to use in python.

    # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
    # The following inputs are layers or table views: "testPoint"
    arcpy.CalculateField_management(in_table="testPoint", field="HourField", expression="arcpy.time.ParseDateTimeString( !datefield! ).strftime('%H')", expression_type="PYTHON_9.3", code_block="")
    

You can also rewrite how this is written in python now you know how it should be structured (I have used your values in this one):

expression = "arcpy.time.ParseDateTimeString(!dtrepor!).strftime('%H')"
arcpy.CalculateField_management(saved_Incidents, "mil_time", expression, "PYTHON_9.3")
Related Question