如何在Python中重新计算几天?

问题描述 投票:1回答:2

出于我正在制作的Web API查询的目的,我正在尝试格式化由管道(“|”)分隔的一堆日期,向后计数七天,并将每个日期添加到复合字符串中。我阅读了文档,并将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 / June 2,2015 | SomePage / June 1,2015 | 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 / June 1,2015 | SomePage / 2015年6月31日| SomePage / 2015年6月30日| SomePage / 2015年6月29日| SomePage / 2015年6月28日| SomePage / June 27,2015 | SomePage / 2015年6月26日

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

  1. 为什么这样实现?
  2. 我该怎么办才能得到我想要的东西?

编辑:第二次看,我写的功能甚至无法处理多年之间的移动。说真的,有什么更好的方法呢?日期时间文档(https://docs.python.org/3/library/datetime.html#datetime.timedelta.resolution)非常密集。

python date
2个回答
5
投票

不,那根本不是什么时间。它完全符合您的期望。

错误只在你的代码中:你总是从datetime.date.today()打印月份,而不是从pythonic_date打印。

打印格式化日期的更好方法是使用strftime的单个调用:

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

1
投票

您可以考虑使用arrow来处理日期,它会让您的生活更轻松。

import arrow

def someMethod():
    fulldates = []
    for date in [arrow.now().replace(days=-i) for i in range(0, 8)]:
        fulldates.append("SomePage/{fmtdate}".format(fmtdate=date.format("MMM D, YYYY")))
    return '|'.join(fulldates)

print(someMethod())

输出是

SomePage/Jun 3, 2015|SomePage/Jun 2, 2015|SomePage/Jun 1, 2015|SomePage/May 31, 2015|SomePage/May 30, 2015|SomePage/May 29, 2015|SomePage/May 28, 2015|SomePage/May 27, 2015
© www.soinside.com 2019 - 2024. All rights reserved.