如何排序字符串中的日期? (蟒蛇)

时间:2018-10-12 01:25:52

标签: python

我只尝试过

from datetime import datetime
my_dates = ['5-Nov-18', '25-Mar-17', '1-Nov-18', '7 Mar 17']
my_dates.sort(key=lambda date: datetime.strptime(date, "%d-%b-%y"))
print(my_dates)

但是我该如何处理像这样的日期格式

my_dates = ['05 Nov 2018', '25 Mar 2017', '01 Nov 2018', '07 Mar 2017']

3 个答案:

答案 0 :(得分:2)

想到的一个优雅的解决方案是用破折号替换所有空格,如下所示:

// Every iteration of loop counts triplet with 
// first element as arr[i]. 
for (int i = 0; i < n - 2; i++) { 

    // Initialize other two elements as corner 
    // elements of subarray arr[j+1..k] 
    int j = i + 1, k = n - 1; 

    // Use Meet in the Middle concept 
    while (j < k) { 

        // If sum of current triplet is more or equal, 
        // move right corner to look for smaller values 
        if (arr[i] + arr[j] + arr[k] >= sum) 
            k--; 

        // Else move left corner 
        else { 

            // This is important. For current i and j, 
            // there are total k-j third elements. 
            for (int x = j + 1; x <= k; x++) 
                cout << arr[i] << ", " << arr[j] 
                     << ", " << arr[x] << endl; 
            j++; 
        } 
    } 
} 

答案 1 :(得分:0)

如果您要查找的只是您提供的特定日期集,只需更改strptime()中的格式:

my_dates = ['05 Nov 2018', '25 Mar 2017', '01 Nov 2018', '07 Mar 2017']
my_dates.sort(key=lambda date: datetime.strptime(date, "%d %b %Y"))

# Change the last %y to %Y

但是,如果您的list中有 个日期格式,则可以准备list个可能预期的字符串格式,并定义自己的函数以针对每种格式进行解析:

def func(date, formats):
    for frmt in formats:
        try:
            str_date = datetime.strptime(date, frmt)
            return str_date
        except ValueError:
            continue

    # might want to consider handling a scenario when nothing is returned

my_formats = ['%d-%b-%y', '%d %b %y', '%d %b %Y']
my_dates = ['5-Nov-18', '25-Mar-17', '1-Nov-18', '7 Mar 17', '05 Nov 2018', '25 Mar 2017', '01 Nov 2018', '07 Mar 2017']
my_dates.sort(key=lambda date: func(date, my_formats))
print(my_dates)

# ['7 Mar 17', '07 Mar 2017', '25-Mar-17', '25 Mar 2017', '1-Nov-18', '01 Nov 2018', '5-Nov-18', '05 Nov 2018']

此处需要说明的是,如果出现意外的日期格式,该函数将返回None,因此将无法正确排序。如果这是一个问题,当所有解析尝试均失败时,您可能想在func()的末尾添加一些处理。一些开发人员可能还会说避免使用try...except...,但是我只能采用这种方式。

答案 2 :(得分:0)

日期是10px 0对象后可以排序

datetime