Add and subtract days to a Date in Python 2

A few days back in the place where i work in the moment one of the reports was failing or at least one of the day was missing, the problem was the way of how it was getting the name of a file in it, the code was something like this in the script.

import datetime
now = datetime.datetime.now()
# we need the file of yesterday
myfile = '/home/dev/file_' + str(now.day - 1) + '_' + str(now.month) + '_' + str(now.year) +'.csv'

This look pretty and all but the problem was when the day is 1 the file of yesterday is not present because the day zero doesn't exist, so a better way of doing this is like:

import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(1)
# we need the file of yesterday
myfile = '/home/dev/file_' + str(yesterday.day) + '_' + str(yesterday.month) + '_' + str(yesterday.year) + '.csv'

We can add days if we want like this

source

No comments: