0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Pythonで今日の週数を取得

Last updated at Posted at 2023-11-02

はじめに

Pythonの備忘録です。

内容

今日が月の何週目なのかを割り出す。

main.py
import calendar
import datetime

def get_week_of_month(year, month, day):
    month_calendar = calendar.monthcalendar(year, month)
    for index, week in enumerate(month_calendar):
        if day in week:
            return index + 1

# 使用例
today = datetime.date.today()
week_of_month = get_week_of_month(today.year, today.month, today.day)

print(f'{today}{week_of_month}週目の週です。')

# 1月1日の場合  2023-01-01は1週目の週です。

使うライブラリ、モジュール

  • schedule
  • datetime

押さえておくべき点

  • scheduleは一番最初の曜日は日曜日
  • indexは0からのため+1がないと0週目になってしまうため必要。
  • enumerateでindex、要素を同時にループ処理できる組込み関数。

参考にしたサイト

Qiita書き方メモ

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?