每个月的第二个星期二

2024-05-08 10:48:53 发布

您现在位置:Python中文网/ 问答频道 /正文

如何获得本月第二个上周二的日期

import calendar
todayyear= date.datetime.today().year
todayday = date.datetime.today().day
c = calendar.TextCalendar(calendar.SUNDAY)
str = c.formatmonth(todayyear,todayday)
print(str)

    October 2020
Su Mo Tu We Th Fr Sa
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

我需要打印出本月第二个上周二的日期,在这个特殊情况下是20号,但它应该适用于任何月份。请告知如何做到这一点


Tags: importtodaydatetimedateyearcalendarprintday
3条回答

救命啊

您将需要执行以下操作:

  1. 获取当月的最后日期
  2. 使用相对detla将该日期转换为一天
  3. 按日期将一天倒推到星期二(这是一个月的最后一个星期二)
  4. 从该日期减去一周

正如你所知道的,注意日期和日期

似乎您可以从^{}获取所有日期,并按日期和月份进行筛选。然后用[-2]索引倒数第二个

import calendar

c = calendar.Calendar()
year = 2020
day = 1

for month in range(1, 13):
    secondLastTues = list(filter(lambda d:d[3] == day and d[1] == month, 
                                 c.itermonthdays4(year, month)))[-2]
    print(secondLastTues)

结果:

(2020, 1, 21, 1)
(2020, 2, 18, 1)
(2020, 3, 24, 1)
(2020, 4, 21, 1)
(2020, 5, 19, 1)
(2020, 6, 23, 1)
(2020, 7, 21, 1)
(2020, 8, 18, 1)
(2020, 9, 22, 1)
(2020, 10, 20, 1)
(2020, 11, 17, 1)
(2020, 12, 22, 1)

你可以试试这个

weeks=str.split('\n')
if len(weeks[-1].split())<3: print(weeks[-3][2])
else: print(weeks[-2][2])

这将在上周二第二次印刷。希望这是有帮助的。如果不清楚,你可以发表评论

相关问题 更多 >