LoginSignup
5
8

More than 5 years have passed since last update.

Pythonメモ:現在の月を取得

Posted at

取り出す形式が色々あり、ややこしそうだったのでメモ。
基本的にはcalendarというモジュールを使うとよさげ。

import calendar

cal = calendar.Calendar()    # calendarオブジェクトを作成
# calendar.Calendar(1)のように、週はじめ扱いにする曜日を指定できる。0~6で、デフォルトは0(月曜)。

### 上記Calendarクラスで決めた通りに予定を所得。以下のような形式がある。 ###

cal.itermonthdays(int_year,int_month)
# イテレータ形式。日を順番に取り出せる。

cal.itermonthdays2(int_year,int_month)
# こちらは日と一緒に曜日も取得できる。(day,week_num)というタプルを順番に取得。

cal.itermonthdates(int_year,int_month)
# こちらはdatetime.date(year,month,day)の形。

cal.monthdayscalendar(int_year,int_month)
# [[0,0,1,2,3,4,5],[6,7..],[...]]という感じで週ごとの日を配列で取れる。

### なお、いずれも月初や月末の週には前後の月の月末や月初が入ってくることがあるので注意!


## ちなみにある月の日数のみを知りたい場合は ##
calendar.monthrange(int_year,int_month)
# でOK。1日の曜日(要るのだろうか・・)と合計日数がタプルで返ってくる。

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8