I have built a script that generates files daily and names them by the date that they are generated. However, I then need to delete these files after 1 month, and have found it to be a bit confusing. I believe that the following will work, but I would like to know if Python has a built in feature that allows for this a bit more Pythonicly and elegently.
Note that this code handles files that are at the end of a month with more days than the following month by deleting all files from last month when it reaches the last day of this month.
if today.month != 1:
if today.day == days_in_month[today.month] and days_in_month[today.month] < days_in_month[today.month - 1]:
for x in range(days_in_month[today.month],days_in_month[today.month-1]+1):
date = date(today.year,today.month-1,x)
fname = str(date)+".stub"
remove(fname)
else:
date = date(today.year-1,12,x)
fname = str(date)+".stub"
remove(fname)
Take a look at Python’s datetime module, it has some classes that should simplify this a lot. You should be able to create a
datetime.datetimeobject from your file name usingdatetime.datetime.strptime(), and another for the current time usingdatetime.datetime.now(). You can then subtract one from the other to get adatetime.timedeltaobject that you can use to figure out the difference between the dates.