ShipGES

datePart() but in python

Blog Post created by ShipGES on Jan 25, 2018

Datetimes.  I don't work with datetime fields often, but when I do I'm usually trying to extract one or more parts from one. I know I can load existing modules; instead, I built a python function for the field calculator that behaves like the simple datePart() function in VB.  Maybe others will find this useful too.

 

def datePart( outpart, ArcGISDateField ):
    # outpart must be one of these: "YYYY" | "M" | "D" | "hh" | "mm" | "ss"
    # ArcGISDateField 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.extend(["00:00:00","AM"])
    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])
    else:
        outparts["hh"] = int(inparts[1][0]) + 12

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

__esri_field_calculator_splitter__
datePart("",)

Outcomes