Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Checking if file is created today

I am trying to see if a certain file was created today. I am using Python. Does anyone have an idea on how the python code for this should be?

I did some research, and people suggested timedelta. However, I was confused on how to use this check whether its made today.

Would appreciate any help.

Thank you.

like image 559
sye Avatar asked Mar 02 '18 22:03

sye


People also ask

How can I tell when a Python file was created?

Use the stat() method of a pathlib object To get the creation and modification time of a file, use the stat( ) method of a pathlib object. This method returns the metadata and various information related to a file, such as file size, creation, and modification time.


2 Answers

You could try something like this, where I put some files in a subdirectory called "so_test" from where I called the script:

import os
import datetime as dt

today = dt.datetime.now().date()

for file in os.listdir('so_test/'):
    filetime = dt.datetime.fromtimestamp(
            os.path.getctime('so_test/' + file))
    print(filetime)
    if filetime.date() == today:
        print('true')
like image 155
roganjosh Avatar answered Sep 22 '22 09:09

roganjosh


You might trying using a combination of datetime and pathlib:

from datetime import date
from pathlib import Path

path = Path('file.txt')
timestamp = date.fromtimestamp(path.stat().st_mtime)
if date.today() == timestamp:
    #Do Something
like image 43
Mike Peder Avatar answered Sep 21 '22 09:09

Mike Peder