【问题标题】:How to subtract a day from datetime format in python? [duplicate]如何从python中的日期时间格式中减去一天? [复制]
【发布时间】:2014-07-05 04:51:01
【问题描述】:

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

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

【问题讨论】:

    标签: python datetime subtraction


    【解决方案1】:
    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"))
    

    这将准确地输出你想要的。

    【讨论】:

    • 我的代码中已将其注释掉
    • 您的代码中有一行注释掉了,但是您将 current_date 设置为等于 timedelta。你需要确保你实际上是在减去。
    • 正如@lafferjm 所说,注释行是问题所在;因为它实际上并没有做你认为它正在做的事情
    • 抱歉重复发帖
    • 感谢 mike 实际上会使用它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 2015-11-26
    • 2020-01-14
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    相关资源
    最近更新 更多