在文件夹Python中读取两个日期之间的文件

我正在尝试读取startdate和之间的文件夹中的文件名enddate。(Datestamp在文件名上)


我正在尝试这样的事情。有没有更好或更有效的方法可以做到这一点?我在该文件夹中有成千上万个文件,但是基于开始/结束日期值,通常我之间会有一个很小的百分比文件。


startdate = "05/05/2013"

enddate = "06/06/2013"

mypath = "C:\\somepath\\"

onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]

for filetoread in onlyfiles:

  filesBetweenDate = [ f for f in time.strftime('%m/%d/%Y',   time.gmtime(os.path.getmtime(somepath+filetoread ))) if f > startdate and f < enddate]



潇湘沐
浏览 179回答 2
2回答

繁花如伊

这应该可以解决问题,它具有几个不错的额外功能,并且只需循环一次即可。import calendarfrom datetime import datetimeimport osimport glob, osmypath = "/Users/craigmj/"timefmt = "%Y%m%d %H:%M:%S"start = calendar.timegm(datetime.strptime("20130128 00:00:00", timefmt).timetuple())end = calendar.timegm(datetime.strptime("20130601 00:00:00", timefmt).timetuple())def test(f):&nbsp; &nbsp; if (not os.path.isfile(f)):&nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) = os.stat(f)&nbsp; &nbsp; return start<=ctime and end>=ctimefiles = [f for f in glob.glob(os.path.join(mypath, "*")) if test(f)]for f in files:&nbsp; &nbsp;print(f)首先,我使用,glob.glob以便您可以在选择文件时使用通配符。如果您可以更具体地选择要选择的文件(例如,如果文件中包含日期戳,则可以节省时间)。其次,我ctime在test函数中使用,但是您可以轻松使用mtime-上次修改时间。最后,我是针对时间的,而不仅仅是针对日期的。我不确定100%唯一的事情是这是否在所有时区都是安全的。在深入研究文档以做出决定之前,您可能需要使用示例进行检查。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python