简体   繁体   English

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

[英]Python: Compare creation directory time with datetime.timedelta

I try to wire a little script in order to find if a directory file was created in the las 24 hours 我尝试连接一个小脚本以查找是否在las 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

So i trying with "datetime" and .timedelta to perform the maths, but i not able to get the creation time from the directory. 所以我尝试使用“ datetime”和.timedelta来执行数学运算,但是我无法从目录中获取创建时间。

import datetime

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

Thanks for your time :D 谢谢您的时间:D

os.path.getctime(path) returns "seconds since epoch" (Unix time). os.path.getctime(path)返回“自纪元以来的秒数”(Unix时间)。 To compare it with the current time, use time.time() : 要将其与当前时间进行比较,请使用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() returns the creation time for path on Windows but on other systems (Unix) it may return the time of the last metadata change . getctime()返回Windows上path的创建时间,但在其他系统(Unix)上,它可能返回上一次元数据更改的时间

See also, Find if 24 hrs have passed between datetimes - Python . 另请参阅查找日期时间之间是否经过了24小时-Python

Here's one solution 这是一个解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM