按年、月和日对字符串进行排序

或格罗曼

我对 Python 很陌生。

基本问题:从目录中提取按年、月和日排序的文件名列表

我正在编写一个搜索最新 bak 的脚本

目录中的文件并将其导入数据库。

文件具有以下格式:

MyDB_05-09-2017.bak

MyDB_05-10-2017.bak

我希望通过文件名提取最新的 bak 文件。

我想按年、月和日对文件进行排序。

这是我尝试过的一些基本实现:

import glob,os,re
from datetime import datetime

# SQL server backup directory
os.chdir('C:\\SQLServerBackups')

# invoke the sql script to drop the database if exists
os.system('C:\\SQLServerBackups\\database_sql_scripts\\drop_database.bat')

# find the latest .bak file and rename it to target

file_list = glob.glob('*.bak')
latest_bak_file = file_list[0]
latest_year = 0
latest_month = 0
latest_day = 0

for file in file_list:
    print(file)
    del_list = re.split('[-._]',file)
    temp_latest_year = int(del_list[3])
    temp_latest_month = int(del_list[1])
    temp_latest_day = int(del_list[2])

    if temp_latest_year > latest_year:
        latest_year = temp_latest_year
        latest_month = temp_latest_month
        latest_day = temp_latest_day
    elif temp_latest_year == latest_year:
        if temp_latest_month > latest_month:
            latest_month = temp_latest_month
            latest_day = temp_latest_day
        elif temp_latest_month == latest_month:
            if temp_latest_day > latest_day:
                latest_day = temp_latest_day
                latest_bak_file = file

print(latest_bak_file)

关于如何更好地实施它的任何建议?

我希望有一个按年、月和日排序的文件名列表。

尼尔斯·维尔纳

您可以定义一个排序键函数,该函数返回您想要排序的字段:

import re

fnames = [
    "MyDB_05-10-2017.bak",
    "MyDB_05-09-2017.bak",
]

def sortkey(x):
    parts = re.split('[-._]', x)
    return [int(parts[3]), int(parts[1]), int(parts[2])]

sorted_fnames = sorted(fnames, key=sortkey)

或者,正如@Klaus D 所说,datetime.strptime在您的搜索键中使用:

sorted_fnames = sorted(fnames, key=lambda x: datetime.datetime.strptime(x, 'MyDB_%d-%m-%Y.bak'))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何根据名称和查询字符串按字母顺序对对象数组进行排序?

如何从字符串日期获取日,月,年?

使用Java从字符串中检索月,日和年的值

从字符串SQL BigQuery解析年和月

在字符串中按字母顺序对字符进行排序

拆分字符串(生日)以获取日,月,年

Python:如何按字母顺序对字符串中的字母进行排序,以区分大写和小写

按字母顺序,数字顺序和特殊字符对字符串数组进行排序

按年和月对数组排序

验证字符串是否包含年,月,日?

如何以字符串格式“ EEE,MMM d,yyyy”获取int月,日和年

按字符对字符串进行排序

以数字和字符串开头的按列对SQL Server表进行数值排序

从“日期”列中以连续字符串格式提取“年”,“月”和“日”

PHP将时间,日,月和年转换为格式化的字符串

按升序和降序对字符串日期数组进行排序

将字符串转换为日期和时间,并提取年,月,日,星期几,小时和分钟

匹配字符串中的天,月和年

将日期字符串(如2017年7月20日)转换为纪元并在Linux中进行比较

按日/月/年将熊猫系列日期字符串分类的最有效方法?

按字符串日期年/月排序元组列表

按数字、字符串和日期类型进行角度排序

Powershell 按特定字符对字符串数组进行排序

按特定元素和该元素的子字符串对元组列表进行排序

如果字符串包含数字和字符,如何按数字对字符串数组进行排序 C++

在 Rstudio 中分隔字符串的日、月和年

Mysql 按日期排序,格式为月(字符串)。日(数),年(数)

按字符串和字母数字对自定义对象进行排序

按计数然后按字符串对排序的字符串集列表进行排序