我正在尝试使用python max在数组中找到最新日期,但我得到的结果不同
预期的结果很好
>>> a = ["10-09-1988","20-10-1999"]
>>> max(a)
'20-10-1999'
自20-10-1999是最新日期
但对于这个
>>> a = ["10-10-1999","20-10-1988"]
>>> max(a)
'20-10-1988'
预期输出
10-10-1999
自10-10-1999是最新日期,但即将到来20-10-1988
如何在数组中获取python中元素的最新日期(日期格式为dd-mm-yyy)
以上我希望(10-10-1999)作为输出
答案 0 :(得分:2)
您需要使用N1
将字符串转换为datetime对象:
=SUM(arrayFriendlyUDF(D1:L1))
答案 1 :(得分:0)
您可以将字符串转换为datetime
对象,或者以下代码可以执行此操作:
>>> a = ["10-09-1988","20-02-1989","20-09-1988"]
>>> max(a,key=lambda x:(x[6:10],x[3:5],x[:2]))
'20-02-1989'
比将字符串转换为datetime
对象更有效:
>>> import timeit
>>> s = """
... a=['28-07-2002', '12-02-1976', '23-10-1967', '27-04-1913', '05-06-1901', '06-12-1964', '04-12-1982', '03-04-1929', '07-02-1943', '03-08-1955']
... import datetime
... max(a, key=lambda x: datetime.datetime.strptime(x, "%d-%m-%Y"))
... """
>>> timeit.timeit(stmt=s,number=10000)
1.0200450420379639
>>> s = """
... a=['28-07-2002', '12-02-1976', '23-10-1967', '27-04-1913', '05-06-1901', '06-12-1964', '04-12-1982', '03-04-1929', '07-02-1943', '03-08-1955']
... import datetime
... max(a,key=lambda x:(x[6:10],x[3:5],x[:2]))
... """
>>> timeit.timeit(stmt=s,number=10000)
0.04339408874511719
答案 2 :(得分:0)
为了比较它们,您需要将表示为字符串的日期转换为datetime
对象。
>>> from datetime import datetime
>>> a = ["10-10-1999","20-10-1988"]
>>> for i, date in enumerate(a):
... a[i] = datetime.strptime(a[i], "%d-%m-%Y")
...
>>> a
[datetime.datetime(1999, 10, 10, 0, 0), datetime.datetime(1988, 10, 20, 0, 0)]
>>> max(a)
datetime.datetime(1999, 10, 10, 0, 0)