python - 本月的周数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3806473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:49:37  来源:igfitidea点击:

python - Week number of the month

pythontimeweek-number

提问by Joao Figueiredo

Does python offer a way to easily get the current week of the month(1:4) ?

python 是否提供了一种轻松获取本月当前周(1:4) 的方法?

采纳答案by Josh

In order to use straight division, the day of month for the date you're looking at needs to be adjusted according to the position (within the week) of the first day of the month. So, if your month happens to start on a Monday (the first day of the week), you can just do division as suggested above. However, if the month starts on a Wednesday, you'll want to add 2 and then do the division. This is all encapsulated in the function below.

为了使用直线除法,需要根据该月第一天的位置(在一周内)调整您正在查看的日期的月份中的第几天。因此,如果您的月份恰好从星期一(一周的第一天)开始,您可以按照上面的建议进行除法。但是,如果该月从星期三开始,您需要添加 2 然后进行除法。这一切都封装在下面的函数中。

from math import ceil

def week_of_month(dt):
    """ Returns the week of the month for the specified date.
    """

    first_day = dt.replace(day=1)

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

    return int(ceil(adjusted_dom/7.0))

回答by Mark Byers

If your first week starts on the first day of the month you can use integer division:

如果您的第一周从该月的第一天开始,您可以使用整数除法:

import datetime
day_of_month = datetime.datetime.now().day
week_number = (day_of_month - 1) // 7 + 1

回答by vito huang

Check out the python calendarmodule

查看python日历模块

回答by Manuel Cuadra Leighton

I found a quite simple way:

我找到了一个非常简单的方法:

import datetime
def week(year, month, day):
    first_week_month = datetime.datetime(year, month, 1).isocalendar()[1]
    if month == 1 and first_week_month > 10:
        first_week_month = 0
    user_date = datetime.datetime(year, month, day).isocalendar()[1]
    if month == 1 and user_date > 10:
        user_date = 0
    return user_date - first_week_month

returns 0 if first week

如果第一周返回 0

回答by Manuel Solorzano

This version could be improved but as a first look in python modules (datetime and calendar), I make this solution, I hope could be useful:

这个版本可以改进,但作为 python 模块(日期时间和日历)的第一眼,我做了这个解决方案,我希望可能有用:

from datetime import datetime
n = datetime.now()
#from django.utils.timezone import now
#n = now() #if you use django with timezone

from calendar import Calendar
cal = Calendar() # week starts Monday
#cal = Calendar(6) # week stars Sunday

weeks = cal.monthdayscalendar(n.year, n.month)
for x in range(len(weeks)):
    if now.day in weeks[x]:
        print x+1

回答by Texas P Renegade

I know this is years old, but I spent a lot of time trying to find this answer. I made my own method and thought I should share.

我知道这已经有好几年了,但我花了很多时间试图找到这个答案。我做了我自己的方法,并认为我应该分享。

The calendar module has a monthcalendar method that returns a 2D array where each row represents a week. For example:

日历模块有一个monthcalendar 方法,它返回一个二维数组,其中每一行代表一个星期。例如:

import calendar
calendar.monthcalendar(2015,9)

result:

结果:

[[0,0,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,0,0,0]]

So numpy's where is your friend here. And I'm in USA so I want the week to start on Sunday and the first week to be labelled 1:

所以numpy的你的朋友在哪里。而且我在美国,所以我希望这一周从周日开始,并且第一周被标记为 1:

import calendar
import numpy as np
calendar.setfirstweekday(6)

def get_week_of_month(year, month, day):
    x = np.array(calendar.monthcalendar(year, month))
    week_of_month = np.where(x==day)[0][0] + 1
    return(week_of_month)

get_week_of_month(2015,9,14)

returns

返回

3

回答by dan

This should do it.

这应该这样做。

#! /usr/bin/env python2

import calendar, datetime

#FUNCTIONS
def week_of_month(date):
    """Determines the week (number) of the month"""

    #Calendar object. 6 = Start on Sunday, 0 = Start on Monday
    cal_object = calendar.Calendar(6)
    month_calendar_dates = cal_object.itermonthdates(date.year,date.month)

    day_of_week = 1
    week_number = 1

    for day in month_calendar_dates:
        #add a week and reset day of week
        if day_of_week > 7:
            week_number += 1
            day_of_week = 1

        if date == day:
            break
        else:
            day_of_week += 1

    return week_number


#MAIN
example_date = datetime.date(2015,9,21)

print "Week",str(week_of_month(example_date))
#Returns 'Week 4'

回答by crazyDiamond

Josh's answer has to be tweaked slightly to accomodate the first day falling on a Sunday.

乔希的答案必须稍微调整以适应周日的第一天。

def get_week_of_month(date):
   first_day = date.replace(day=1)

   day_of_month = date.day

   if(first_day.weekday() == 6):
       adjusted_dom = (1 + first_day.weekday()) / 7
   else:
       adjusted_dom = day_of_month + first_day.weekday()

   return int(ceil(adjusted_dom/7.0))

回答by benelgiac

Josh' answer seems the best but I think that we should take into account the fact that a week belongs to a month only if its Thursday falls into that month. At least that's what the iso says.

乔希的回答似乎是最好的,但我认为我们应该考虑这样一个事实,即只有当星期四属于一个月时,一周才属于一个月。至少iso是这么说的

According to that standard, a month can have up to 5 weeks. A day could belong to a month, but the week it belongs tomay not.

根据该标准,一个月最多可以有 5 周。一天可能属于一个月,但它所属的星期可能不属于

I have taken into account that just by adding a simple

我已经考虑到只需添加一个简单的

if (first_day.weekday()>3) :
        return ret_val-1
    else:
        return ret_val

where ret_val is exactly Josh's calculated value. Tested on June 2017 (has 5 weeks) and on September 2017. Passing '2017-09-01' returns 0 because that day belongs to a week that does not belong to September.

其中 ret_val 正是 Josh 的计算值。在 2017 年 6 月(有 5 周)和 2017 年 9 月进行了测试。通过“2017-09-01”返回 0,因为那一天属于不属于 9 月的一周。

The most correct way would be to have the method return both the week number and the month namethe input day belongs to.

最正确的方法是让该方法返回输入日期所属的周数和月份名称

回答by Prateek Dorwal

Check out the package Pendulum

查看包装Pendulum

>>> dt = pendulum.parse('2018-09-30')
>>> dt.week_of_month
5