Dap Dap - 1 year ago 108
Python Question

How to subtract a day from datetime format in python?

I'm trying print the day ranges from today up to a year ago. So i can apply this to a sql query in my other code.

I know my algorithm works but i need to subtract 1 day from the format '2014-05-15'
Here is the code

from datetime import date, timedelta
import datetime
current_date = datetime.date.today()
datecounter = 0
while datecounter != 365:
print current_date
date_start = current_date
print date_start
# current_date = current_date.timedelta(days=1)
print current_date
print 'the date is between', date_start, 'and', current_date
datecounter += 1

im looking for this code to output

the date is between 2014-05-16 and 2014-05-15
the date is between 2014-05-15 and 2014-04-14


i wrote a contrived example based on the logic, if you would like to run it yourself, you may better understand what i am trying to do.

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
curdate = 5
for i in x:
print curdate
date_start = curdate
curdate = curdate - 1
# print curdate

print ' the date is between', date_start, 'and', curdate
print ' ---------- '

Answer Source

See this stackoverflow question


Your code could also do with some cleaning:

from datetime import date, timedelta

cur_date = date.today()
for i in xrange(365):
    start_date = cur_date
    cur_date = cur_date-timedelta(days=1)
    print "the date is between {} and {}".format(start_date.strftime("%Y-%m-%d"), cur_date.strftime("%Y-%m-%d"))

This will output exactly what you want.