0

** 问题 ** 我正在尝试打开(在 python 中)超过当前名称中日期戳 3 天的文件。示例:2016_08_18_23_10_00 - JPN - MLB - Mickeymouse v Burgerface.ply。到目前为止,我可以创建一个日期变量,但是我不知道如何在文件名中搜索这个变量。我想我需要先将其转换为字符串?

from datetime import datetime, timedelta
import os
import re
path = "C:\Users\michael.lawton\Desktop\Housekeeper"

## create variable d where current date time is subtracted by 3 days ##

days_to_subtract = 3
d = datetime.today() - timedelta(days=days_to_subtract)

print d

## open file in dir where date in filename = d or older ##

for filename in os.listdir(path):
if re.match(d, filename):
    with open(os.path.join(path, filename), 'r') as f:
        print line,

任何帮助都感激不尽

4

2 回答 2

0

你可以用strptime这个。它会将您的字符串(假设它的格式正确)转换为一个日期时间对象,您可以使用该对象根据文件名比较您的文件是否早于 3 天:

from datetime import datetime

...

lines = []
for filename in os.listdir(path):
  date_filename = datetime.strptime(filename.split(" ")[0], '%Y_%m_%d_%H_%M_%S')
  if date_filename < datetime.datetime.now()-datetime.timedelta(days=days_to_subtract):
    with open(os.path.join(path, filename), 'r') as f:
      lines.extend(f.readlines()) # put all lines into array

如果文件名是2016_08_18_23_10_00 - JPN - MLB - Mickeymouse v Burgerface.ply日期时间部分,将使用filename.split(" ")[0]. 然后我们可以使用它来检查它是否超过三天使用datetime.timedelta

于 2016-09-21T08:47:49.433 回答
0

要打开给定目录中名称中包含超过 3 天的时间戳的所有文件:

#!/usr/bin/env python2
import os
import time

DAY = 86400 # POSIX day in seconds
three_days_ago = time.time() - 3 * DAY
for filename in os.listdir(dirpath):
    time_string = filename.partition(" ")[0]
    try:
        timestamp = time.mktime(time.strptime(time_string, '%Y_%m_%d_%H_%M_%S'))
    except Exception: # can't get timestamp
        continue
    if timestamp < three_days_ago: # old enough to open
        with open(os.path.join(dirpath, filename)) as file: # assume it is a file
            for line in file:
                print line,

该代码假定时间戳位于本地时区。mktime()在 C可以访问tz 数据库的平台上,它可能会考虑 DST 转换(如果在您的情况下文件是 72 小时还是 73 小时都无关紧要,那么忽略这一段)。

考虑使用文件元数据,例如“文件的最后修改时间”,而不是从文件名中提取时间戳:timestamp = os.path.getmtime(path).

于 2016-09-21T17:28:03.433 回答