How to populate a new field with integer year extracted from date field in arcpy

2510
10
Jump to solution
04-21-2020 11:17 AM
RobertTrotter
New Contributor III

I recognize this is a question that has been asked before (I have included some links and strings below that are related), but I have not found a solution, and I am likely making a mistake that is now opaque to me, so I am hoping for assistance here.

The solutions I have found seem to use Arcade, VB, and/or the GUI Field Calculator (the Field Calculator works, but I would like to automate the process in a script).

What I I would like to do is create a new field "inspectionyear", and populate it with an integer for the year, extracted from another date field "inspection_date".

Creating the new field is straight forward.

# Import modules
import arcpy, datetime # Provides access to arcpy tools
from arcpy import time
from datetime import *

# Add a new field to contain the year integer
arcpy.env.workspace = "C/DataFiles/DataSource.dbf"
arcpy.DeleteField_management("DataSource.dbf","inspectionyear") # If a field with the name "yearvalue" already exists, delete it
arcpy.AddField_management("DataSource.dbf","yearfield","INTEGER") # Create the field that will hold the year integers.

However, I have not successfully extracted the year values and added them to the new field.

I have tried using the GUI Field Calculator as shown:

The process runs and closes successfully, with no errors, however, the inspectionyear field remains populated with <NULL>

I have also tried using the VB function in arcpy

arcpy.CalculateField_management(inputtable,"inspectionyear",DatePart("yyyy",[fulldate]),"VB")

which produces:

NameError: name 'DatePart' is not defined

and I have also tried:

datevalues = datetime.datetime.strftime(!inspection_date!,"%-m/%-d/%Y")

To simply retrieve the year, but end up with a syntax error.

Can someone recommend a way to retrieve the year value, or point me in the direction of a guide?  I have already explored quite a few links, including but not limited to the following.

Arcade approach

Matching question posed by other user, but not answered

Field Calculator GUI method that ran, but did not populate the field

Info on generating datetime objects

Thank you,

Robert

0 Kudos
10 Replies
JoshuaBixby
MVP Esteemed Contributor

Using Python, try the following in your expression:

!inspection_date!.date().year

I can't remember the exact version, possibly 10.5.x, Esri switched from having Esri date fields returned as Python strings to Python datetime.