[GIS] Calculate Date field in ArcPy

arcpydatetime

I'm trying to use arcpy.ExtractValuesToPoints() to get raster values to a points feature class for several raster files (8760). The goal is to get a time-slice view of how the values at certain locations change over time.

I'm fairly well versed in Python as well as the built-in datetime module. The trouble that I'm having is saving the date-time values to a table in ArcGIS.

(I've gotten a similar approach to work using arcpy.da.InsertCursor() but this approach is very process-intensive and I've concluded that it isn't a viable approach for what I'm trying to do. Plus I'd rather not re-invent the wheel and use the ArcGIS function: ExtractValuesToPoints() instead.)

To give a little background, I'm using dates that require datetime precision to the hour so I've elected to use a File Geodatabase to accommodate that feature (since shapefiles can only handle the date portion).

I'm trying to solve for a single case as I can create a solution for iterating over the 8760 files that I'm working with.

So far this is what I have:

import arcpy
import os

GRID_Table = "E:\HRRR.gdb\GRID_Table"               # GRID_Table is an ArcGIS table
SPP_LMP_Points = "E:\HRRR.gdb\SPP\SPP_LMP_Points"   # that contains datetime and                  
out_path = "C:\scratch.gdb"                         # raster_path pairs.


row1 = []                                           # Get date_time and raster_path      
for row in arcpy.SearchCursor(GRID_Table):          # from every entry in GRID_Table
    row1.append((row.DateTime, row.RasterPath))     #

date_time = row1[0][0]                              # Set date_time to the first 
raster_path = row1[0][1]                            # entry 

out_path_shp = os.path.join(out_path, os.path.basename(raster_path))  # Generate 
                                                                      # output path.

arcpy.sa.ExtractValuesToPoints(SPP_LMP_Points, raster_path, out_path_shp)

arcpy.AddField_management(out_path_shp, "DateTime", "DATE")

arcpy.CalculateField_management(out_path_shp, "DateTime", 
                                "!DateTime! = {0}".format(date_time), 
                                "PYTHON_9.3")

This all works fine and doesn't report any exceptions or errors. The trouble that I'm having is that the call to arcpy.CalculateField_management() doesn't populate the DateTime field. Instead I get a NULL value in the table.

Any thoughts?

Best Answer

You just don't quite have the quotes right in your expression.You need double quotes around your datetime. Also, you shouldn't have !DateTime! = as part of it.

Try:

arcpy.CalculateField_management(out_path_shp, "DateTime", 
                                '"' + date_time + '"', 
                                "PYTHON_9.3")