Home > front end >  Filename to date and then sort in Python
Filename to date and then sort in Python

Time:01-23

I have many many batch files in format ddmmyy-00. How can I convert ddmmyy for sorting purposes?

for name in glob.glob(path, recursive=True):
  basename=os.path.basename(name)
  newname=os.path.spltext(basename)[0]
  ##what code do I have to put here to convert 'newname' to date format?##

CodePudding user response:

Use datetime:

import datetime
datestring = '050621'
newname = datetime.datetime.strptime(datestring, '%d%m%y')
# datetime.datetime(2021, 6, 5, 0, 0)

The newname can be compared to other instances, and can thus be sorted. You can see the complete list of format codes here.

CodePudding user response:

If you have a list of file names, this code below is a good start:

from datetime import datetime

def parse_item(input_str):
  parts = input_str.split("-")

  return {
    "file_name": input_str,
    "date": datetime.strptime(parts[0], '%d%m%y'),
    "file_no": int(parts[1]),
  }

inputs = [
  "021222-01",
  "011222-00"
]
mapping_files = [parse_item(input) for input in inputs]
sorted_files = sorted(mapping_files, key=lambda x: x["date"])

print(sorted_files)

# outputs
# [{'file_name': '011222-00', 'date': datetime.datetime(2022, 12, 1, 0, 0), 'file_no': 0}, {'file_name': '021222-01', 'date': datetime.datetime(2022, 12, 2, 0, 0), 'file_no': 1}]
  •  Tags:  
  • Related