[GIS] Calculate QUARTER from Date field using ArcGIS Field Calculator

arcgis-desktopfield-calculatorpython-parservbscript

I currently have a Date field in the format of MM/DD/YYYY.

My goal here is to convert the Dates into 1 of 4 quarters, along with the Year. The field to be created will be called QTR_YR.

My first question is what data type do I need to make the QTR_YR field? Should it be Integer (Short or Long), or Date, or Double?

I am old school so I'd prefer VBA but I can use Python.

Best Answer

The query below in VBA should return a string that looks like "Q2 1990" for each record. All credits go to @EvilGenius for this one.

VBA Sample

"Q" & DatePart ( "q", [MyDate] ) & " " & DatePart ( "yyyy", [MyDate] )

Just make sure your quarter field "QTR_YR" is a Text/String type. If the format "Q2 1990" is not to your taste, you can tweak the format. Concatenation in VBA is done by the ampersand "&" not "+" like most other languages.

Let us know if this works.


Update: As requested, the solution in ArcPy with the UpdateCursor would be:

import arcpy
import datetime

def GetQuarter(month):
    """
    Define a function to return the quarter of a month (Jan=1, Dec=12).
    Where:
        0-3 = Q1
        4-6 = Q2
        7-9 = Q3
        10-12 = Q4
    """
    if 0 <= int(month) <= 3:
        return 1
    elif 4 <= int(month) <= 6:
        return 2
    elif 7 <= int(month) <= 9:
        return 3
    elif 10 <= int(month) <= 12:
        return 4
    else:
        raise ValueError, "Month needs to be between 0-12"

fc = r"C:\Users\MyUsername\Desktop\Working.gdb\TestPoints" # Change to path to your feature class.
with arcpy.da.UpdateCursor(fc, ["MyDate", "MyQuarter"]) as cursor: # Change "MyDate" and "MyQuarter" to your respective field names.
    for row in cursor:
        date = row[0] # A datetime object
        quarter = "Q{0} {1}".format(GetQuarter(date.month), date.year) # The quarter string will look like "Q2 1990".
        row[1] = quarter # Assign quarter value to current row.
        cursor.updateRow(row) # Update (save) row.
del cursor