【问题标题】:Is there a function in python that returns the i-th day of the week within the month?python中是否有一个函数可以返回一个月内一周中的第i天?
【发布时间】:2019-11-07 03:25:40
【问题描述】:

给定一个日期,有必要知道它是否对应于该月一周的第一天、第二天、第三天(等等)。 例如: 如果条目是 2017-01-04,则返回:1th 每月的星期三。 如果条目是 2017-01-25,则返回:4th 每月的星期三。 如果条目是 2018-10-18,则返回:3th 每月的星期四。

我已经搜索了日期时间库,但找不到任何返回该值的库。

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    使用weekday:

    from datetime import datetime
    
    weekday_map = {0: 'Monday',
                   1: 'Tuesday',
                   2: 'Wednesday',
                   3: 'Thursday',
                   4: 'Friday',
                   5: 'Saturday',
                   6: 'Sunday'}
    
    suffix_map = {1: 'st',
                  2: 'nd',
                  3: 'rd',
                  4: 'th',
                  5: 'th'}
    
    def which_weekday(date):
        dt = datetime.strptime(date, '%Y-%m-%d')
        which = (dt.day - 1) // 7 + 1
        weekday = weekday_map[dt.weekday()]
        return f'{which}{suffix_map[which]} {weekday} of the month'
    
    print(which_weekday('2017-01-04'))
    print(which_weekday('2017-01-25'))
    print(which_weekday('2018-10-18'))
    

    输出:

    1st Wednesday of the month
    4th Wednesday of the month
    3rd Thursday of the month
    

    【讨论】:

    • 我尝试了很多日期,它有效,非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 2011-12-09
    • 1970-01-01
    • 2013-08-30
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多