0

I try to wire a little script in order to find if a directory file was created in the las 24 hours

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.

import datetime

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

Thanks for your time :D

2 Answers2

0

os.path.getctime(path) returns "seconds since epoch" (Unix time). To compare it with the current time, use 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.

See also, Find if 24 hrs have passed between datetimes - Python.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
-1

Here's one solution

if time.mktime(time.localtime()) - os.path.getctime(path) < 24 * 60 * 60:
    ....
Stanton
  • 497
  • 3
  • 14
  • Note the change, use localtime just in case your machine isn't UTC. – Stanton Sep 15 '15 at 20:46
  • `mktime(localtime())` may return a wrong value during DST transitions (with ambiguous local time). [Use `time.time()` instead](http://stackoverflow.com/a/32597555/4279). – jfs Sep 16 '15 at 00:00