[GIS] Python Max Function in Field Calculator for Date values

arcgis-10.5arcgis-desktopdatefield-calculatorpython-parser

I have 4 fields with Date Time values, and created a new field (Date type as well) which takes the most recent date from these 4 fields. I have tried using the Max python in the field calculator to populate this new field, but it does not use the most recent date from these 4 fields. Does this function not work with Datetime values, or is there another function for this that I am not able to find on these forums.

max([!field1!, !field2!, !field3!, !field4!])

I am on 10.5. When I have two fields that have a date within the same month, it will not read the rest of the date correctly. (See picture attached)

enter image description here

When I run the following updated code it fails and says it is a syntax error.

enter image description here

enter image description here

With the current code, it reads the first number in the day to select the most recent date. (As shown below). It does not use the correct chronological format, even though the strptime format worked previously.
enter image description here

Best Answer

You need to convert your date into datetime object for max() to work correctly. It appears field calculator doesn't see the value as a datetime object. You may need to adjust the date format to suit your region date settings. See Strptime Behavior in the Python docs.

Using the Python Parser, select Show Codeblock. In the Pre-logic script code:

from datetime import datetime
def dtmax(*args):
    f = '%m/%d/%Y %I:%M:%S %p'
    dlist= list()
    for d in args:
        if d:
            dlist.append(datetime.strptime(d, f))
    return max(dlist)

Expression:

dtmax(!DateField1!, !DateField2!, !DateField3!, !DateField4!)