I have a field called Abandoned Year (short integer data type) that I am trying to populate with a four digit year from a column called Decommission Date (Date data type). I have done this in the past using the DatePart( ) VB function but how do I accomplish this same task in a Python field calculation?

Here is the code written in VB:

AbandonedYear = DatePart ("YYYY", [DecommissionDate])


2 Answers 2


Try this:

AbandonedYear = datetime.datetime.strptime( !DecommissionDate! , '%m/%d/%Y %I:%M:%S %p').year

You may need to change the format, if so a reference for those format strings is found here: Python Documentation

  • Thanks! I got this to work, datetime.datetime.strptime(!DecommissionDate!, '%m/%d/%Y').year
    – user19300
    Jun 20, 2013 at 14:26

I built a field calculator expression using Python that behaves like that nice DatePart function in VB. I just [Load...] my *.cal file whenever I need it. Yes, I know there's much more Pythonic ways of doing this, but I just like the familiar simplicity and not having to remember that ArcGIS treats datetimes as text strings during field calculations.

def datePart( outpart, ArcGISDateField ):

    # var outpart must be one: "YYYY" | "M" | "D" | "hh" | "mm" | "ss"

    # var indatetime must take the form of either "M/D/YYYY" or "M/D/YYYY hh:mm:ss AP"
    # My Windows Date and Time settings ensure this form.

    inparts = ArcGISDateField.split(" ")
    if( len(inparts) == 1):
    inparts[0] = inparts[0].split("/")
    inparts[1] = inparts[1].split(":")   

    # build a dictionary to store the date and time parts
    outparts = {}
    outparts["M"] = int(inparts[0][0])
    outparts["D"] = int(inparts[0][1])
    outparts["YYYY"] = int(inparts[0][2])
    outparts["mm"] = int(inparts[1][1])
    outparts["ss"] = int(inparts[1][2])
    if( inparts[2] == "AM" ):
        outparts["hh"] = int(inparts[1][0])
        outparts["hh"] = int(inparts[1][0]) + 12

    # Grab and return the value of the date part I want
    return outparts[outpart]

Outfield = datePart("hh",!timestamp!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.