Python-在前一周遍历

时间:2018-09-12 12:26:09

标签: python python-3.x python-2.7

我是python的新手,我有以下用例:

请参考下面的日历:

enter image description here

今天的日期是2018-09-12。 我想在其他条件下对前一天进行一些计算。 我已经使用以下代码检索了昨天的日期和日期:

yesterday_date = datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d')
yesterday_day = datetime.strftime(datetime.now() - timedelta(1), '%A')

现在,我想在上周的同一天进行一些计算。即:我想获取同一天的上周的日期 (星期二)。因此,基本上,我想连续迭代与昨天日期同一天的上周日期并进行一些计算。

Yesterday Date : 2018-09-11

Yesterday Day : Tuesday

所以我的输出应该像:

2018-09-04
2018-08-28
2018-08-21
2018-08-14
2018-08-07

以此类推。

我该如何实现?

3 个答案:

答案 0 :(得分:3)

假设您要打印昨天日期的最后5个实例:

yesterday = datetime.now() - timedelta(days=1)
for i in range(0, 5):
    prev_date = yesterday - timedelta(days=i*7)
    print(datetime.strftime(prev_date, '%Y-%m-%d'))

或者如果您想要日期时间对象的列表:

yesterday = datetime.now() - timedelta(days=1)
prev_dates = [yesterday - timedelta(days=i*7) for i in range(0, 5)]

答案 1 :(得分:1)

这可以通过while循环并使用timedelta(days=days_to_subtract)

来完成。
from datetime import datetime, timedelta
yesterday_date = datetime.today() - timedelta(days=1)  
some_condition = True
i = 0
while (some_condition):
    # do your process with yesterday_date and maybe change the value of some_condition
    i+=1
    yesterday_date -= timedelta(days=7*i)

答案 2 :(得分:1)

尝试循环并使用临时变量:

from datetime import datetime, timedelta
yesterday_date = datetime.strftime(datetime.now() - timedelta(1), '%Y-%m-%d')
yesterday_day = datetime.strftime(datetime.now() - timedelta(1), '%A')
date_temp = datetime.now() - timedelta(1)
for i in range(5):
    yesterday_date = datetime.strftime(date_temp - timedelta(7), '%Y-%m-%d')
    yesterday_day = datetime.strftime(date_temp - timedelta(7), '%A')
    date_temp = date_temp - timedelta(7)
    print(yesterday_date, yesterday_day, date_temp)

输出:

2018-09-04 Tuesday 2018-09-04 17:04:43.470056
2018-08-28 Tuesday 2018-08-28 17:04:43.470056
2018-08-21 Tuesday 2018-08-21 17:04:43.470056
2018-08-14 Tuesday 2018-08-14 17:04:43.470056
2018-08-07 Tuesday 2018-08-07 17:04:43.470056