【问题标题】:Comparing File Dates in a Directory比较目录中的文件日期
【发布时间】:2015-05-20 16:11:00
【问题描述】:

我正在尝试用 Python 编写一个脚本来根据照片的创建日期上传一系列照片。我有一个问题,将每个文件的日期与我想要的日期之前和之后的日期进行比较,以便我可以创建一个数组来循环上传。这是我所拥有的:

from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time, datetime

array = []

area = "/home/user/blah"
# Edit the path to match your desired folder between the ""
os.chdir(area)
retval = os.getcwd()
# Puts you in the desired directory

dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
entries = ((os.stat(path), path) for path in entries)
entries = ((stat[ST_CTIME], path)
           for stat, path in entries if S_ISREG(stat[ST_MODE]))

for cdate, path in sorted(entries):
    filedate = time.ctime(cdate)
    if filedate < datetime.date(2015,03,13) and filedate > datetime.date(2015,02,17):
        print time.ctime(cdate)
        print os.path.basename(path)

有没有办法用 ctime 做到这一点,还是有更好的方法?

【问题讨论】:

  • 你用的是什么版本的 Python?

标签: python datetime ctime


【解决方案1】:

ctime 返回字符串表示,如果要与时间比较,则应比较时间戳或日期时间类。

for cdate, path in sorted(entries):
    # compare by timestamp
    #if cdate < time.mktime(datetime.date(2015,03,13).timetuple()) and \
    #    cdate > time.mktime(datetime.date(2014,02,17).timetuple()):

    # compare by datetime
    filedate = datetime.datetime.fromtimestamp(cdate)
    if filedate < datetime.datetime(2015,03,13) and \
            filedate > datetime.datetime(2014,02,17):
        print time.ctime(cdate)
        print os.path.basename(path)

【讨论】:

  • 哦,很酷,我以为 fromtimestamp 只适用于 timedelta。酷,我刚刚学到了一些东西。谢谢!
【解决方案2】:

这里不需要os.chdir()。处理绝对文件名很好。您可以使用 list-comp 简化选择标准,datetimeos.path.isfileos.path.getctime,例如:

import os
from datetime import datetime

files = [
    fname
    for fname in sorted(os.listdir(dirpath))
    if os.path.isfile(fname) and
    datetime(2015, 2, 17) <= datetime.fromtimestamp(os.path.getctime(fname)) <= datetime(2015, 3, 13)
]

这将返回两个日期之间所有文件的列表...

我猜您正在使用 Python 2.x,否则 datetime.date(2015,03,13) 会在 3.x 中为您提供 SyntaxError。请注意这一点,因为 03 是八进制文字,并且恰好适用于您的情况 - 但 08/09 会因为它们对八进制无效而中断。

【讨论】:

    猜你喜欢
    • 2013-01-26
    • 2014-03-05
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多