How to get Sundays of last 90 days (3 months) from current date using datetime in Python(如何在 Python 中使用 datetime 从当前日期获取最近 90 天(3 个月)的星期日)
问题描述
我正在尝试使用日期时间从 python 中的当前日期获取最近 90 天(星期日 3 个月星期日)的日期.我可以在周日获得最后 3 个月,但不能从当前日期开始.使用此代码,我将获得本月和过去 2 个月(共 3 个月)的星期日列表.
I am trying to get a date of last 90 days Sundays (3 months Sunday) from the current date in python using datetime. I am able to get last 3 months Sunday but not from current date. With this code i am getting list of Sunday from the current month and last 2 month (total 3 months).
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
使用上面的代码,我得到了这个
With above code, i am getting this
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(格式)举例
datetime
- 基本日期和时间类型pprint
- 数据漂亮的打印机
- Python DateTime, TimeDelta, Strftime(Format) with Examples
datetime
- Basic date and time typespprint
- Data pretty printer
这篇关于如何在 Python 中使用 datetime 从当前日期获取最近 90 天(3 个月)的星期日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中使用 datetime 从当前日期获取最近


- 如何将一个类的函数分成多个文件? 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 沿轴计算直方图 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12