[Tutor] deleting files that are older than x days old

Brian van den Broek bvande at po-box.mcgill.ca
Wed Jul 13 20:30:22 CEST 2005


Mike Hansen said unto the world upon 13/07/2005 12:54:
>  From a python program, I want to delete certain files that are older than x 
> days old.
> 
> To get the time that the file was last modified, it looks like I need to use 
> os.path.getmtime(path). This gives you the time represented in the number of 
> seconds from the epoch.
> 
> I'd like to convert this into a datetime object, but I can't seem to figure out 
> how. Once it's a datetime object, I can do simple (datetime.datetime.today() - 
> filedatetime).days to figure out the days old.
> 
> How do you convert a time represented in seconds from the epoch into a datetime 
> object?
> 
> Mike

Hi Mike,

Kent gave you the answer to the question you asked. But, for what you 
are doing, I'd think about something sort of along the lines of Bob's 
suggestion.

The way below avoids going through datetime objects:

 >>> t = time.time()
 >>> t -= 5 * 24 * 60 * 60
 >>> # t is now 5 days back from current seconds from epoch
 >>> def older_than_n_days(n, time_stamp):
	return time.time() - time_stamp < n * 24 * 60 * 60

 >>> for i in range(3, 8):
	print older_than_n_days(i, t)

	
False
False
False
True
True
 >>>

Best,

Brian vdB


More information about the Tutor mailing list