Home > Software design >  how to get number of days since a file was created in python
how to get number of days since a file was created in python

Time:06-09

I need to get the number of days since a file was created, and i tried this code:

import os.path, time
import datetime
from datetime import date

path = 'D:/Reg.txt'

creation_date = "created: %s" % time.ctime(os.path.getctime(path))

today = datetime.datetime.today()

delta = today - creation_date

print(delta.days)

but i get this error message: unsupported operand type(s) for -: 'datetime.datetime' and 'str'

CodePudding user response:

You should convert creation date into datetime format from string

import os.path, time import datetime from datetime import date

path = 'D:/Reg.txt'

creation_date = "created: %s" % time.ctime(os.path.getctime(path))

creation_date=datetime.strptime(creation_date, '%m-%d-%Y').date()

today = datetime.datetime.today()

delta = today - creation_date

print(delta.days)

CodePudding user response:

In your code, creation_date was a string. To make it workable, convert it to a datetime object using the datetime.fromtimestamp(epochtime) from datetime library. Example below:

import os.path, time
import datetime
from datetime import date

path = 'D:/Reg.txt'

creation_date = datetime.datetime.fromtimestamp(os.path.getctime(path))

today = datetime.datetime.today()

delta = today - creation_date

print(delta.days)

Note that datetime.datetime.fromtimestamp converts a number to a datetime object so you just need to pass in the epoch time directly. In your case, this was os.path.getctime(path)

  • Related