我正在尝试格式化一连串用竖线(“ |”)分隔的日期,以进行我要进行的Web API查询,将时间倒退7天,并将每个日期添加到复合字符串中。我阅读了文档,然后拼凑起来,我需要使用date.today()和datetime.timedelta的组合。我写方法:

def someMethod():
    ret = ''
    pythonic_date = datetime.date.today()
    for i in range(0, 8):
        pythonic_date -= datetime.timedelta(days=1)
        ret += "SomePage" + datetime.date.today().strftime("%B" + " ")
        ret += str(pythonic_date.day).lstrip('0')
        ret += ", " + str(pythonic_date.year) + "|"
    ret = ret[0:len(ret) - 1]
    return ret


我希望得到以下输出:


  SomePage / 2015年6月2日| SomePage / 2015年6月1日| SomePage / 2015年5月31日| SomePage / 2015年5月30日| SomePage / 2015年5月29日| SomePage / 2015年5月28日| SomePage / 2015年5月27日| SomePage / 2015年5月26日


相反,我得到以下输出:


  SomePage / 2015年6月2日| SomePage / 2015年6月1日| SomePage / 2015年6月31日| SomePage / 2015年6月30日| SomePage / 2015年6月29日| SomePage / 2015年6月28日| SomePage / 2015年6月27日| SomePage / 2015年6月26日


我看到在这里使用timedelta只是天真地循环返回日期类对象中的day字段,而不是对整个日期进行操作。我有两个问题:


为什么以这种方式实施?
我该怎么做才能得到我想要的东西?


编辑:从第二个角度看,我编写的函数甚至无法处理几年之间的变化。认真地说,有什么更好的方法?日期时间文档(https://docs.python.org/3/library/datetime.html#datetime.timedelta.resolution)非常密集。

最佳答案

不,那根本不是timedelta要做的。它完全符合您的期望。

错误仅存在于您的代码中:您始终从datetime.date.today()而不是pythonic_date打印月份。

打印格式化日期的一种更好的方法是使用一次对strftime的调用:

ret += "SomePage" + pythonic_date.strftime("%B %-d, %Y") + "|"

关于python - 如何在Python中计算过去的时间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30621840/

10-12 18:18