开发者

Datetime problem at start of month in Python

I have a function that removes a file after a certain amount of time. The problem is that it works at later parts of the month, but when I try and remove 7 days from the start of the month it will not substract into the previous month. Does anyone know how to get this to work? The code is below that works out the date and removes the days.

today = datetime.date.today() # Today's date Binary
todaystr = datetime.date.to开发者_JAVA技巧day().isoformat() # Todays date as a string
minus_seven = today.replace(day=today.day-7).isoformat() # Removes 7 days

Thanks for any help.


minus_seven = today - datetime.timedelta(days = 7)


The reason this breaks is that today is a datetime.date; and as the docs say, that means that today.day is:

Between 1 and the number of days in the given month of the given year.

You can see why this works later in the month; but for the first few days of the month you end up with a negative value.

The docs immediately go on to document the correct way to do what you're trying to do:

date2 = date1 - timedelta Computes date2 such that date2 + timedelta == date1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜