【问题标题】:How to obtain day of the month from day of the week?如何从星期几获取月份中的某一天?
【发布时间】:2018-04-09 08:58:29
【问题描述】:

我正在尝试让 python 在输入一周中的某一天时返回月份的日期,例如: 2018 年 4 月的第一个星期日返回 1 或 2018 年 4 月的第三个星期四返回 19

是否有 python 库或数学算法可以做到这一点?我查看了 Zeller 的一致性,但似乎相反。

【问题讨论】:

  • 使用date.weekday 查找每月第一天的工作日。增加工作日差异的价值。添加 7*n 以表示周差。瞧。
  • 该死的我怎么错过了。谢谢@MrT!
  • 与日期有关的大部分内容都可以在 datetime 或(鲜为人知的)calendar 库中找到。

标签: python date math


【解决方案1】:

从您的输入字符串中分离所有值,然后从该年的该月获取该天的所有日期。

这是一个很大的尝试:

import calendar
import re

c = calendar.Calendar(firstweekday=calendar.SUNDAY)

string = "1st Sunday of April 2018"
string.split().pop(2)
string_list = string.split()
year = int(string_list[4])
month = list(calendar.month_name).index(string_list[3])
day_num = list(calendar.day_name).index(string_list[1])
which = int(re.search(r'\d+', string_list[0]).group())

monthcal = c.monthdatescalendar(year,month)
date = [day for week in monthcal for day in week if \
            day.weekday() == day_num and \
            day.month == month][which-1]

print(date.day)

【讨论】:

    猜你喜欢
    • 2014-11-04
    • 1970-01-01
    • 2020-12-14
    • 2021-12-16
    • 2022-01-21
    • 1970-01-01
    • 2013-05-28
    • 2021-07-19
    • 1970-01-01
    相关资源
    最近更新 更多