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)
When I run the following updated code it fails and says it is a syntax error.
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
1 Answer 1
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!)
-
1Would be nice if this was generalized as
dtmax(*args)
instead of requiring 4 fields exactly.Paul– Paul2017年06月16日 17:36:17 +00:00Commented Jun 16, 2017 at 17:36 -
@Paul Good idea, updated.2017年06月16日 18:06:38 +00:00Commented Jun 16, 2017 at 18:06
-
With args I do not need to list the fields?Purplepeopleeater– Purplepeopleeater2017年06月16日 19:01:22 +00:00Commented Jun 16, 2017 at 19:01
-
1@Paul That's correct, and how I had first written it while testing, however when learning I prefer things written out as (in my opinion) it can make things a bit clearer as to what is happening in the code. Once Python is more understood by the user, then we can look at other ways to write it.2017年06月16日 20:26:44 +00:00Commented Jun 16, 2017 at 20:26
-
1@Purplepeopleeater Please give more info. Edit your question and add a description and some detail about what is happening now. Don't remove anything from your existing question, just add to the bottom of it.2017年06月23日 20:11:22 +00:00Commented Jun 23, 2017 at 20:11
Explore related questions
See similar questions with these tags.
max( [!Date1!, !Date2!]
), butmax( !Date1!, !Date2! )
also works. I am on ArcGIS 10.5. Which version do you use? Also, what kind of values do you have in your fields, please post. Also, make sure all of them are ofDate
type.max
?