Python Forum

Full Version: Need to identify only files created today.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I need to copy a file if it was accessed/created today.
I could make a batch file for that but I want to use Python.
It is probably a combination of some kind of File Stat and
time.now()
.
not sure how to do that.
Thank you.
Here's one way to go about it:

import os
from datetime import datetime

todays_date = datetime.now ()
today = todays_date.date ()
path = '/path/to/files/'

for filename in os.listdir (path) :
	file_time = os.path.getmtime (path + filename)
	file_date = datetime.fromtimestamp (file_time)
	file_day = file_date.date ()
	if file_day == today :
		print (f'File to copy is {path + filename}.')
A Generator-Example:

import datetime
from pathlib import Path


def find_files_today(path):
    today = datetime.date.today()
    for file in Path().rglob("*"):
        try:
            is_file = file.is_file() # <- possible PermissionError
        except PermissionError:
            continue
        if not is_file:
            continue
        mdate = datetime.date.fromtimestamp(file.stat().st_mtime)
        if is_file and today == mdate:
            yield file
        
That's amazing! Dance
Thank you both!
There are at least two different ways to get today's file stat.
Love it!

from datetime import datetime
And :
import datetime
By the way, it seems both of these come from the same module:
import datetime
Could you elaborate, please?
I'm sure there are a lot of people who would live to understand it.
Thank you again!
datetime is both the module name and the class name. If you import the module with:

import datetime
then you would have to use the class like this:

file_date = datetime.datetime.fromtimestamp (file_time)
if you import like this:
from datetime import datetime
Then you don't need to use datetime.datetime but only the class name, like this:

file_date = datetime.fromtimestamp (file_time)
Outstanding!
Thank you again for the code and the coaching!
I really appreciate it!