簡體   English   中英

如何在python中找出本月的第幾周?

[英]How to find out week no of the month in python?

我見過很多方法來確定一年中的一周。 就像通過給出指令datetime.date(2016, 2, 14).isocalendar()[1]我得到6作為輸出。 這意味着 2016 年 2 月 14 日屬於一年中的第 6 周。 但是我找不到任何方法可以找到一個月中的一周。

意味着如果我將輸入作為some_function(2016,2,16)我應該得到輸出3 ,表示我 2016 年 2 月 16 日是 2016 年 2 月的第 3 周

[這是與類似可用問題不同的問題,在這里我問的是找到月份的第幾周而不是一年的第幾周]

import datetime
def week_number_of_month(date_value):
    week_number = (date_value.isocalendar()[1] - date_value.replace(day=1).isocalendar()[1] + 1)
    if week_number == -46:
        week_number = 6
   return week_number
        
date_given = datetime.datetime(year=2018, month=12, day=31).date()
        
week_number_of_month(date_given)

這個功能完成了我想要的工作

from math import ceil

def week_of_month(dt):

    first_day = dt.replace(day=1)

    dom = dt.day
    adjusted_dom = dom + first_day.weekday()

    return int(ceil(adjusted_dom/7.0))

我從這個 StackOverFlow 答案中得到了這個功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM