python对日期型数据排序_Python:按日期时间对文件进行更详细的排序

我尝试下面的代码

# retrieve the file information from a selected folder

# sort the files by last modified date/time and display in order newest file first

# tested with Python24 vegaseat 21jan2006

import os, glob, time

# use a folder you have ...

root = 'D:\\Zz1\\Cartoons\\' # one specific folder

#root = 'D:\\Zz1\\*' # all the subfolders too

date_file_list = []

for folder in glob.glob(root):

print "folder =", folder

# select the type of file, for instance *.jpg or all files *.*

for file in glob.glob(folder + '/*.*'):

# retrieves the stats for the current file as a tuple

# (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)

# the tuple element mtime at index 8 is the last-modified-date

stats = os.stat(file)

# create tuple (year yyyy, month(1-12), day(1-31), hour(0-23), minute(0-59), second(0-59),

# weekday(0-6, 0 is monday), Julian day(1-366), daylight flag(-1,0 or 1)) from seconds since epoch

# note: this tuple can be sorted properly by date and time

lastmod_date = time.localtime(stats[8])

#print image_file, lastmod_date # test

# create list of tuples ready for sorting by date

date_file_tuple = lastmod_date, file

date_file_list.append(date_file_tuple)

#print date_file_list # test

date_file_list.sort()

date_file_list.reverse() # newest mod date now first

print "%-40s %s" % ("filename:", "last modified:")

for file in date_file_list:

# extract just the filename

folder, file_name = os.path.split(file[1])

# convert date tuple to MM/DD/YYYY HH:MM:SS format

file_date = time.strftime("%m/%d/%y %H:%M:%S", file[0])

print "%-40s %s" % (file_name, file_date)希望这会有所帮助

谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值