如何使用 Python 中的日期时间从当前日期获取过去 90 天(3 个月)的星期日



我正在尝试使用 datetime 从 python 中的当前日期获取过去 90 天的星期日(3 个月星期日)的日期。我能够获得最后 3 个月的星期日,但不能从当前日期开始。使用此代码,我从当前月份和过去 2 个月(总共 3 个月)获得星期日列表。

from datetime import date, timedelta, datetime
def list_sunday(year, month, day):
try:
for i in range(1,4):
d = date(year, month, day)
d += timedelta(days = 6 -d.weekday())
while d.month==month:
yield d
d += timedelta(days =+ 7)
if month > 1:
month = month - 1
else:
month = 12
year = year - 1
i+=1
except Exception as e:
log.error("XXX %s" % str(e))
for d in list_sunday(2019, 4, 05):
print d

使用上面的代码,我得到了这个

2019-04-07
2019-04-14
2019-04-21
2019-04-28
2019-03-10
2019-03-17
2019-03-24
2019-03-31
2019-02-10
2019-02-17
2019-02-24

这就是我想要得到的,

2019-03-10
2019-03-17
2019-03-24
2019-03-31
2019-02-10
2019-02-17
2019-02-24
2019-01-06
2019-01-13
2019-01-20
2019-01-27

有人可以帮忙吗?

from datetime import date, timedelta
from pprint import pprint
def is_sunday(day):
return day.weekday() == 6
def sundays_within_last_x_days(num_days = 90):
result = []
end_date = date.today()
start_date = end_date - timedelta(days = num_days)
while start_date <= end_date:
if is_sunday(start_date):
result.append(start_date)
start_date += timedelta(days = 1)
return result
if __name__ == "__main__":
dates = sundays_within_last_x_days(30)
pprint(dates)

资源

  • Python DateTime, TimeDelta, Strftime(Format) with Example
  • datetime- 基本日期和时间类型
  • pprint- 数据漂亮的打印机

这可能会根据您的草稿为您提供更好的方法。有关如何了解有关此内容的更多信息。请点击下一个链接

from datetime import date, timedelta
def all_sundays(year):
# January 1st of the given year
dt = date(year, 1, 1)
# First Sunday of the given year       
dt += timedelta(days = 6 - dt.weekday())  
while dt.year == year:
yield dt
dt += timedelta(days = 7)
for s in all_sundays(2020):
print(s)

输出

2020年01月05日 2020年01月12日 2020年01月19
日 2020年01月26
日 2020年02
月02日

2020年12月06日 2020年12月13日 2020年12月20日2020
年12月27日

最新更新