如何在Python中检查文件是否超过3个月?
我对在Python中处理时间很感兴趣。我可以使用 os.path.getmtime()
这个函数来获取一个文件的最后修改时间,方法如下:
import os.path, time
os.path.getmtime(oldLoc)
我需要进行一些测试,看看这个时间是否在过去三个月内,但我对Python中各种时间选项感到很困惑。
有没有人能给我一些建议呢?谢谢!
8 个回答
26
为了让事情更清楚,你可以在这里使用一些日期时间的简单计算。
>>> import datetime
>>> today = datetime.datetime.today()
>>> modified_date = datetime.datetime.fromtimestamp(os.path.getmtime('yourfile'))
>>> duration = today - modified_date
>>> duration.days > 90 # approximation again. there is no direct support for months.
True
29
time.time() - os.path.getmtime(oldLoc) > (3 * 30 * 24 * 60 * 60)
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。
2
如果你想要准确的天数,可以使用 calendar
模块和 datetime 一起使用,比如:
import calendar
import datetime
def total_number_of_days(number_of_months=3):
c = calendar.Calendar()
d = datetime.datetime.now()
total = 0
for offset in range(0, number_of_months):
current_month = d.month - offset
while current_month <= 0:
current_month = 12 + current_month
days_in_month = len( filter(lambda x: x != 0, c.itermonthdays(d.year, current_month)))
total = total + days_in_month
return total
然后把 total_number_of_days()
的结果放入其他人提供的日期计算代码中。