如何在python中从datetime格式中减去一天?

时间:2014-05-16 16:29:57

标签: python datetime subtraction

我尝试打印从今天到一年前的日期范围。所以我可以在我的其他代码中将它应用于sql查询 我知道我的算法有效但我需要从格式中减去1天#2014; 2014-05-15' 这是代码

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

即时寻找此代码输出

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

我根据逻辑写了一个人为的例子,如果你想自己运行它,你可能会更好地理解我想要做的事情。

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 ' ---------- '

1 个答案:

答案 0 :(得分:4)

curdate=curdate-datetime.timedelta(days=1)

请参阅this stackoverflow question

修改

您的代码也可以进行一些清理:

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"))

这将输出您想要的内容。