8

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.

sye
  • 201
  • 3
  • 4
  • 10
  • [This](https://stackoverflow.com/a/18126680/4799172) will give you the date that a file was created. `timedelta` is only relevant if you wanted to check whether a file was created in another time period other than the current one e.g. yesterday. – roganjosh Mar 02 '18 at 22:36

2 Answers2

11

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')
roganjosh
  • 12,594
  • 4
  • 29
  • 46
  • When trying this over a network the date returned is today instead of the file date. This one worked for me: 'import os import datetime as dt dt.datetime.now().date() == dt.datetime.fromtimestamp(os.path.getctime('so_test/' + file)).date()' – Leo May 28 '20 at 19:29
  • @Leo I'm not sure what you mean by "over a network". Are you saying that it screws with database timezones or something? I posted this answer a while back so I'm happy to try shore it up if it needs it – roganjosh May 28 '20 at 19:38
  • 1
    hello, I was too quick with converting it to your set-up and found the cause. What I found is that getctime didn't work for me to get the file date, I think it should be getmtime – Leo May 28 '20 at 19:41
  • @Leo disagree. It's in the title that they want the creation date, not a modification date – roganjosh May 28 '20 at 19:50
  • thank you very much for prompt replying and checking. Your answer I agree with. I've found the cause on my side. My files were copied today so creation date is today and modified date is older. – Leo May 28 '20 at 20:08
  • @Leo glad you got it sorted :) I don't even remember posting this answer so it probably can be improved; I think it might have been off-the-cuff but the view count is kinda high. I'll review it, thanks for bringing it up – roganjosh May 28 '20 at 20:49
6

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
Mike Peder
  • 728
  • 4
  • 8