如何在Python中查看文件是否超过3个月?

Luk*_*e B 8 python time

我很想在Python中操纵时间.我可以使用os.path.getmtime()函数获取文件的(上次修改)年龄:

import os.path, time    

os.path.getmtime(oldLoc)
Run Code Online (Sandbox Code Playgroud)

我需要运行某种测试来查看这个时间是否在过去三个月内,但我对Python中所有可用的时间选项感到困惑.

有人可以提供任何见解吗?亲切的问候.

Ign*_*ams 20

time.time() - os.path.getmtime(oldLoc) > (3 * 30 * 24 * 60 * 60)
Run Code Online (Sandbox Code Playgroud)

  • @Nicholas:你讨厌银行业的运作方式. (4认同)
  • ...这有点接近“月”:-) (2认同)

Sen*_*ran 20

为了清楚起见,您可以在这里使用一些日期时间关节.

>>> 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
Run Code Online (Sandbox Code Playgroud)


jfs*_*jfs 5

要查找文件是否早于 3 个日历月,您可以使用dateutil.relativedelta

#!/usr/bin/env python
import os
from datetime import datetime
from dateutil.relativedelta import relativedelta # $ pip install python-dateutil

three_months_ago = datetime.now() - relativedelta(months=3)
file_time = datetime.fromtimestamp(os.path.getmtime(filename))
if file_time < three_months_ago:
    print("%s is older than 3 months" % filename)
Run Code Online (Sandbox Code Playgroud)

在这种情况下,“过去 3 个月”中的确切天数可能与 90 天不同。如果您正好需要 90 天,请执行以下操作:

from datetime import datetime, timedelta

three_months_ago = datetime.now() - timedelta(days=90)
Run Code Online (Sandbox Code Playgroud)

如果要考虑本地 utc 偏移量的变化,请参阅查找日期时间之间是否已过去 24 小时 - Python


A L*_*Lee 2

如果您需要确切的天数,可以将该calendar模块与日期时间结合使用,例如,

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
Run Code Online (Sandbox Code Playgroud)

然后将结果输入total_number_of_days()其他人为日期算术提供的代码中。