콘솔워크

python 날짜 n월 n주차 구하기 본문

프로그래밍/python

python 날짜 n월 n주차 구하기

콘솔워크 2023. 5. 30. 20:57
반응형

규칙

1. 주의 시작은 월요일이다. 

2. 월~일 까지 중 월이 다른 경우 어느 월을 선택할지 기준은 더 많은 쪽을 선택하면 된다.

3. 따라서, 더 많은 쪽을 나누는 기준은 "목요일"이다.

 

예를들어, 위의 규칙으로 2023년 5월 30일은 몇주차 일까?

6월 1주차일까 5월 5주차일까?

정답은 6월 1주차이다.

왜냐하면 목요일이 6월달이기 때문이다.

from datetime import datetime, date, timedelta
import lunardate
import calendar
import numpy as np

last_day_of_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leap_year_last_day_of_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

def get_today_week_name():

    today_week_name = ""

    today = datetime.now()
    year = today.year
    month = today.month
    day = today.day

    x = np.array(calendar.monthcalendar(year, month))
    week_of_month = np.where(x == day)[0][0] + 1
    first_day_of_month = date(year, month, 1).weekday()
    flag = 0
    if first_day_of_month > 3:
        flag = 1
    week_of_month -= flag
    if week_of_month == 0:
        day_of_week = date(year, month, day).weekday()
        if day_of_week > 3:  # 목요일
            if month == 1:
                year -= 1
                month = 12
            else:
                month -= 1
            if year % 4 == 0:
                day = leap_year_last_day_of_month[month - 1]
            else:
                day = last_day_of_month[month - 1]

            x = np.array(calendar.monthcalendar(year, month))
            week_of_month = np.where(x == day)[0][0] + 1
            if date(year, month, 1).weekday() > 3:
                week_of_month -= 1
        else:
            week_of_month = 1
    elif week_of_month == 5:

        if month == 12:
            year += 1
            month = 1
        else:
            month += 1
        day = 1
        day_of_week = date(year, month, day).weekday()

        if day_of_week <= 3:  # 목요일
            week_of_month = 1

    if week_of_month == 1:
        today_week_name = f"{month}월 첫째 주"
    elif week_of_month == 2:
        today_week_name = f"{month}월 둘째 주"
    elif week_of_month == 3:
        today_week_name = f"{month}월 셋째 주"
    elif week_of_month == 4:
        today_week_name = f"{month}월 넷째 주"
    elif week_of_month == 5:
        today_week_name = f"{month}월 다섯째 주"

    return today_week_name


if __name__ == "__main__":
    # Example usage
    today_week_name = get_today_week_name()
    print(today_week_name)

 

위의 코드에서 3이랑 비교하는게 많이 나오는데 상수 3은 목요일을 의미한다.

 

위에 만들어진 get_today_week_name() 은 오늘은 몇월 몇주차인지 결과를 알려주는 함수이다.

 

오늘이 아니라 특정일이 궁금하다면, 날짜를 파라미터로 받아서 리턴하는 함수로 변경하면 된다.

반응형