如何在Python中重新计算日期?

时间:2015-06-03 13:40:13

标签: python date

我正在尝试格式化由管道(“|”)分隔的一堆日期,用于我正在进行的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 / 2015年6月2日| SomePage / 2015年6月1日| SomePage / 2015年5月31日| SomePage / 2015年5月30日| SomePage / 2015年5月29日| SomePage / 2015年5月28日| SomePage / 5月27日, 2015 | SomePage / 2015年5月26日

相反,我得到以下输出:

  

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

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

  1. 为什么这样实现?
  2. 我该怎样做才能得到我想要的东西?
  3. 编辑:再看看,我写的功能甚至无法处理多年之间的移动。说真的,有什么更好的方法呢?日期时间文档(https://docs.python.org/3/library/datetime.html#datetime.timedelta.resolution)非常密集。

2 个答案:

答案 0 :(得分:5)

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

错误只在您的代码中:您始终从my_cookies = requests.utils.dict_from_cookiejar(s.cookies) 打印月份,而不是从datetime.date.today()打印。

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

strftime

答案 1 :(得分: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