每个月底前的天数

发布于 2025-01-17 21:11:15 字数 317 浏览 0 评论 0原文

如何获得“ 2018/01/29',''2018/02/26',哪个是在每个月末之前的第二天,例如从下面的python的日报?

daylist=['2018/01/25','2018/01/26','2018/01/29','2018/01/30','2018/01/31','2018/02/01','2018/02/20','2018/02/23','2018/02/26','2018/02/27','2018/02/28','2018/03/02']

(每秒钟都可以通过日间[-2 :: -2]获得,但我不知道如何在每个月的每个月之前获得第二天)

How to get '2018/01/29', '2018/02/26' which are second days before every end of month, such as from the daylist below in Python?

daylist=['2018/01/25','2018/01/26','2018/01/29','2018/01/30','2018/01/31','2018/02/01','2018/02/20','2018/02/23','2018/02/26','2018/02/27','2018/02/28','2018/03/02']

(Every secondays can be obtained by daylist[-2::-2], but I have no idea how to get second days before every end of the month)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋凉 2025-01-24 21:11:15

您可以通过检查日期是否是一个月结束,然后减去两天的日期来完成此操作。前任:

from datetime import datetime, timedelta

daylist=['2018/01/25','2018/01/26','2018/01/29','2018/01/30','2018/01/31','2018/02/01','2018/02/20','2018/02/23','2018/02/26','2018/02/27','2018/02/28','2018/03/02']

# parse to datetime first
dt_list = [datetime.strptime(d, "%Y/%m/%d") for d in daylist]

# now shift each date by one day and see if the month changes - if so,
# you have a month end...
two_days_before_end = []
for dt in dt_list:
    # assumes the dt_list is sorted:
    if (dt + timedelta(days=1)).month != dt.month:
        two_days_before_end.append(dt-timedelta(days=2))

print(two_days_before_end)
# [datetime.datetime(2018, 1, 29, 0, 0), datetime.datetime(2018, 2, 26, 0, 0)]

You could do that by checking if a date is the end of a month, then subtracting two days to get the date two days before that. Ex:

from datetime import datetime, timedelta

daylist=['2018/01/25','2018/01/26','2018/01/29','2018/01/30','2018/01/31','2018/02/01','2018/02/20','2018/02/23','2018/02/26','2018/02/27','2018/02/28','2018/03/02']

# parse to datetime first
dt_list = [datetime.strptime(d, "%Y/%m/%d") for d in daylist]

# now shift each date by one day and see if the month changes - if so,
# you have a month end...
two_days_before_end = []
for dt in dt_list:
    # assumes the dt_list is sorted:
    if (dt + timedelta(days=1)).month != dt.month:
        two_days_before_end.append(dt-timedelta(days=2))

print(two_days_before_end)
# [datetime.datetime(2018, 1, 29, 0, 0), datetime.datetime(2018, 2, 26, 0, 0)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文