Python:将创建目录时间与datetime.timedelta进行比较

时间:2015-09-15 20:20:49

标签: python time

我尝试连接一个小脚本,以便查找目录文件是否在24小时内创建

import time

path = /some/path/dir
currentTime = time.strftime("%c")
print currentTime   # Tue Sep 15 18:08:54 2015
if os.path.isdir(path):
    created = time.ctime(os.path.getctime(path)) 
    print created   # Thu Sep 25 17:29:28 2014
    if created > 24 hours: # time don't have comparison  
        # do someting

所以我尝试了" datetime"和.timedelta来执行数学运算,但我无法从目录中获得创建时间。

import datetime

print datetime.datetime(os.path.getctime(path))
    # AttributeError: 'module' object has no attribute 'datetimep'

感谢您的时间:D

2 个答案:

答案 0 :(得分:0)

os.path.getctime(path)返回“自纪元以来的秒数”(Unix时间)。要将其与当前时间进行比较,请使用time.time()

import os
import time

DAY = 86400 # seconds -- POSIX day
if (time.time() - os.path.getctime(path)) > DAY:
    print("more than 24 hours have passed")

getctime()返回the creation time for path on Windows but on other systems (Unix) it may return the time of the last metadata change

另见Find if 24 hrs have passed between datetimes - Python

答案 1 :(得分:-1)

这是一个解决方案

if time.mktime(time.localtime()) - os.path.getctime(path) < 24 * 60 * 60:
    ....