如何在python中排序日期?

时间:2019-05-02 19:02:28

标签: python regex sorting date python-2.x

我试图对列表中的日期进行排序,但是日期在字符串元素[EQUIP-X]之后。首先使用正则表达式,取唯一的日期并尝试排序。没用!

我想将字符串[EQUIP-X]Date分开。

files = [filename for root, dirs, files in os.walk(path) for filename in files for date in dateList if filename.endswith(date+".log")]
for item in files:
 reg = re.search(r"(.+]).(\d{2}.\d{2}.\d{4})",item)
 equip = reg.group(1)
 data = reg.group(2)
 namefile = data+'.'+equip 
 print item
  • 组(1)-[EQUIP-X]
  • group(2)-日期

示例字符串:

[EQUIP-4].02.05.2019.log
[EQUIP-2].01.05.2019.log
[EQUIP-1].30.04.2019.log
[EQUIP-3].29.04.2019.log
[EQUIP-1].01.05.2019.log
[EQUIP-5].30.04.2019.log
[EQUIP-1].29.04.2019.log
[EQUIP-5].30.04.2019.log
[EQUIP-3].30.04.2019.log
[EQUIP-1].29.04.2019.log
[EQUIP-2].02.05.2019.log

tutorial之后,一旦我不操纵“日期”而是“ str”,就没有“ str”对象的属性“ sort”。有什么更好的方法呢?当时的想法是拆分并处理日期,然后全部加入

6 个答案:

答案 0 :(得分:2)

您可以根据字符串的末尾减去作为日期解析的最后4个字符(文件扩展名)进行排序。由于日期格式为零填充,因此长度应始终为10个字符,因此字符串拼接应从-14开始(日期为10,扩展名为4)

using System;
using Alea;

namespace Raymarcher
{
    [GpuManaged]
    public class Camera
    {
        [GpuParam]
        public Vector3 origin;
        [GpuParam]
        private Vector3 forward;
        [GpuParam]
        private Vector3 up;
        private Vector3 right;
        private Vector3 screenOrigin;
        private float stepY;
        private float stepX;
        private float sizeX;
        private float sizeY;


        public Camera(Vector3 origin, Vector3 forward,  float fov)
        {
            this.forward = forward.Normalized();
            this.right=(new Vector3(-forward.z,0,forward.x)).Normalized();
            this.up = (right * forward).Normalized();
            this.origin = origin;
        }
        public void SetScreenData(int width, int height)
        {
            sizeY = (width / height) * sizeX;
            stepX =  sizeX/width;
            stepY =  sizeY/height;
            screenOrigin = origin+forward + (up * (sizeY / 2f)) - (right * (sizeX / 2f));
        }

        public Vector3 GetRay(int x, int y)
        {
            return screenOrigin-origin+stepX*x*right-up*y*stepY;
        }
    }
}
from datetime import datetime

files = ['[EQUIP-4].02.05.2019.log',
'[EQUIP-2].01.05.2019.log',
'[EQUIP-1].30.04.2019.log',
'[EQUIP-3].29.04.2019.log',
'[EQUIP-1].01.05.2019.log',
'[EQUIP-5].30.04.2019.log',
'[EQUIP-1].29.04.2019.log',
'[EQUIP-5].30.04.2019.log',
'[EQUIP-3].30.04.2019.log',
'[EQUIP-1].29.04.2019.log',
'[EQUIP-2].02.05.2019.log']

files.sort(key=lambda x: datetime.strptime(x[-14:-4], '%d.%m.%Y'))
print(files)

答案 1 :(得分:1)

python sort函数具有一个key参数,可让您在对元素进行排序之前对其进行修改。

此示例从字符串的末尾提取数字并对其进行排序。

a = ['hello 123', 'pumpkin 542', 'muffin 342']

def get_important_part(string):
    return int(string.split()[1])

print(sorted(a, key=get_important_part))

返回

['hello 123', 'muffin 342', 'pumpkin 542']

答案 2 :(得分:1)

为什么不使用strptimestrftime

dates = ['02.05.2019', '20.05.2019', '11.05.2019', '30.05.2019', '08.05.2019', '09.05.2019']
dates_obj = [datetime.strptime(x,'%d.%m.%Y') for x in dates]
dates_sorted = sorted(dates_obj)
dates_sorted = [x.strftime('%d.%m.%Y') for x in dates_sorted]
print (dates_sorted)

['02/05/2019', '08/05/2019', '09/05/2019', '11/05/2019', '20/05/2019', '30/05/2019']

答案 3 :(得分:1)

您可以将列表转换为熊猫数据框,然后进行相应的排序。按年,月和日排序,然后将索引转换为列表。然后显示按索引(iloc)排序的值。

import pandas as pd
df = pd.DataFrame([('[EQUIP-4].02.05.2019.log')
,('[EQUIP-2].01.05.2019.log')
,('[EQUIP-1].30.04.2019.log')
,('[EQUIP-3].29.04.2019.log')
,('[EQUIP-1].01.05.2019.log')
,('[EQUIP-5].30.04.2019.log')
,('[EQUIP-1].29.04.2019.log')
,('[EQUIP-5].30.04.2019.log')
,('[EQUIP-3].30.04.2019.log')
,('[EQUIP-1].29.04.2019.log')
,('[EQUIP-2].02.05.2019.log')], columns = ['file'])

df.iloc[df['file'] \
      .map(lambda x: pd.to_datetime(x[-14:-4])) \
      .sort_values() \
      .index \
      .tolist()]

结果:

                 file
1   [EQUIP-2].01.05.2019.log
4   [EQUIP-1].01.05.2019.log
0   [EQUIP-4].02.05.2019.log
10  [EQUIP-2].02.05.2019.log
3   [EQUIP-3].29.04.2019.log
6   [EQUIP-1].29.04.2019.log
9   [EQUIP-1].29.04.2019.log
2   [EQUIP-1].30.04.2019.log
5   [EQUIP-5].30.04.2019.log
7   [EQUIP-5].30.04.2019.log
8   [EQUIP-3].30.04.2019.log

答案 4 :(得分:1)

结合@ddg和@Sayse的建议,您可以尝试:

import re
from datetime import datetime

files = ["[EQUIP-4].02.05.2019.log", ...]

files.sort(key = lambda item: datetime.strptime(re.search(r"(?=.)(\d{2}.\d{2}.\d{4})(?=.)", item).group(0), '%d.%m.%Y'), reverse=False)

或以更具可读性的方式:

def getSortValue(item):
  reg = re.search(r"(?=.)(\d{2}.\d{2}.\d{4})(?=.)", item)
  data = reg.group(0)
  return datetime.strptime(data, '%d.%m.%Y')

files.sort(key = getSortValue, reverse = False)

输出:

print('\n'.join(files))

[EQUIP-3].29.04.2019.log
[EQUIP-1].29.04.2019.log
[EQUIP-1].29.04.2019.log
[EQUIP-1].30.04.2019.log
[EQUIP-5].30.04.2019.log
[EQUIP-5].30.04.2019.log
[EQUIP-3].30.04.2019.log
[EQUIP-2].01.05.2019.log
[EQUIP-1].01.05.2019.log
[EQUIP-4].02.05.2019.log
[EQUIP-2].02.05.2019.log

答案 5 :(得分:0)

您可以使用内置的list sort()函数对文件名进行排序,如下所示:

from datetime import datetime
import os  # Even though not used in example code.
from pprint import pprint
import re

#files = [filename for root, dirs, files in os.walk(path) for filename in files for date in dateList if filename.endswith(date+".log")]
files = [
    '[EQUIP-4].02.05.2019.log',
    '[EQUIP-2].01.05.2019.log',
    '[EQUIP-1].30.04.2019.log',
    '[EQUIP-3].29.04.2019.log',
    '[EQUIP-1].01.05.2019.log',
    '[EQUIP-5].30.04.2019.log',
    '[EQUIP-1].29.04.2019.log',
    '[EQUIP-5].30.04.2019.log',
    '[EQUIP-3].30.04.2019.log',
    '[EQUIP-1].29.04.2019.log',
    '[EQUIP-2].02.05.2019.log',
]

def get_date(filename):
    match = re.search(r".+].(\d{2}.\d{2}.\d{4})",filename)
    date_str = match.group(1)
    return datetime.strptime(date_str, '%d.%m.%Y')

files.sort(key=get_date)

pprint(files)

输出:

['[EQUIP-3].29.04.2019.log',
 '[EQUIP-1].29.04.2019.log',
 '[EQUIP-1].29.04.2019.log',
 '[EQUIP-1].30.04.2019.log',
 '[EQUIP-5].30.04.2019.log',
 '[EQUIP-5].30.04.2019.log',
 '[EQUIP-3].30.04.2019.log',
 '[EQUIP-2].01.05.2019.log',
 '[EQUIP-1].01.05.2019.log',
 '[EQUIP-4].02.05.2019.log',
 '[EQUIP-2].02.05.2019.log']