pythonは、月の現在の週(1:4) を簡単に取得する方法を提供していますか?
17 に答える
割り算を利用するには、月の最初の日の位置 (週内) に応じて、見ている日付の日を調整する必要があります。そのため、月がたまたま月曜日 (週の最初の日) から始まる場合は、上記の方法で割り算を行うことができます。ただし、月が水曜日から始まる場合は、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))
私はこれが何年も前のものであることを知っていますが、私はこの答えを見つけるのに多くの時間を費やしました. 私は独自の方法を作成し、共有する必要があると考えました.
calendar モジュールには、各行が週を表す 2D 配列を返す monthcalendar メソッドがあります。例えば:
import calendar
calendar.monthcalendar(2015,9)
結果:
[[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]]
あなたの友達はどこにいるの?そして、私はアメリカにいるので、週を日曜日に開始し、最初の週に 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)
戻り値
3
最初の週が月の最初の日に始まる場合、整数除算を使用できます。
日時のインポート day_of_month = datetime.datetime.now().day 週番号 = (月の日 - 1) // 7 + 1
Pythonカレンダーモジュールをチェックしてください
Josh の回答は、初日が日曜日になるように少し調整する必要があります。
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))
私は非常に簡単な方法を見つけました:
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
最初の週の場合は 0 を返します
次のような月のカレンダーがあるとします。
Mon Tue Wed Thur Fri Sat Sun
1 2 3
4 5 6 7 8 9 10
1 ~ 3 日目は1 週目に属し、4 ~ 10 日目は 2 週目に属します。
この場合、特定の日の week_of_month は次のように計算する必要があると思います。
import datetime
def week_of_month(year, month, day):
weekday_of_day_one = datetime.date(year, month, 1).weekday()
weekday_of_day = datetime.date(year, month, day)
return (day - 1)//7 + 1 + (weekday_of_day < weekday_of_day_one)
ただし、代わりに、1 日が第 1金曜日、第 8 日が第 2金曜日、第 6 日が第 1水曜日のように、その日付の曜日の n 番目を取得したい場合は、単純に(day - 1 )//7 + 1
これでうまくいくはずです。
#! /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'