월초,월말 날짜 구하기:직접구현 혹은 calendar 패키지를 활용

Oni·2023년 1월 25일
0
from datetime import datetime
year, month = datetime.today().year, datetime.today().month

방법 1) 직접



def isLeapYear(year):
    return year % 4 == 0 and year % 100 != 0 or year % 400 == 0

def lastDay(year, month):
    m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    m[1] = 29 if isLeapYear(year) else 28
    return m[month - 1]

def totalDay(year, month, day):
    total = (year - 1) * 365 + (year - 1) // 4 - (year - 1) // 100 + (year - 1) // 400
    for i in range(1, month):
        total += lastDay(year, i)
    return total + day

def weekDay(year, month, day):              # weekDay(year, month, 1)는 공백의 갯수
    return totalDay(year, month, day) % 7

# 월초 
weekDay(year, month, 1)
# 월말
lastDay(year,month)

방법 2) calendar 패키지 활용


import calendar

# 월초
calendar.weekday(year,month,1)+1)%7
# 월말
calendar.monthrange(year, month)[1]
profile
데이터 분석/엔지니어링/ML에 관한 기록

0개의 댓글