Python 시간 및 달력 모듈 활용 가이드

1. 시간과 달력의 기본 활용 방법

# 시간 처리 모듈
import time

# 달력 처리 모듈  
import calendar

# 현재 타임스탬프 값
current_timestamp = time.time()

# 로컬 시간 정보 (튜플 형식)
local_time_info = time.localtime(time.time())

# 날짜 형식 지정
formatted_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

# 특정 월 달력 출력
monthly_calendar = calendar.month(2020, 6)

print(monthly_calendar)

2. 시간 모듈 주요 속성 및 함수

#!/usr/bin/python 
# -*- coding: utf-8 -*-

import time

# 서부 일광절약시간대 오프셋(시간 단위)
dst_offset = time.altzone / 3600

# 그리니치 기준 오프셋 초 수(시간 단위)
gmt_offset = time.timezone / 3600

# 시간대 이름
time_zone_names = time.tzname

# 현재 타임스탬프
timestamp = time.time()

# CPU 시간 반환
processor_time = time.clock()

# 튜플 형태의 시간 정보
local_tuple = time.localtime()
utc_tuple = time.gmtime()

# 튜플을 읽기 가능한 형식으로 변환
readable_time = time.asctime(local_tuple)

# ctime()은 asctime(localtime(secs))와 동일, 인자 없을 시 asctime()과 동일
current_time_string = time.ctime()

# 시간 튜플을 타임스탬프로 변환
converted_timestamp = time.mktime(utc_tuple)

# 지정된 시간 동안 대기
time.sleep(1)

# 시간 튜플을 문자열로 포맷
formatted_str = time.strftime("%Y-%m", utc_tuple)

# 문자열을 시간 튜플로 파싱
parsed_tuple = time.strptime(readable_time, "%a %b %d %H:%M:%S %Y")

# TZ 환경변수 기반 시간 설정 재초기화
# time.tzset()

print(readable_time)
Python에서 사용하는 날짜 및 시간 포맷 기호:
  • %y : 두 자리 연도 표현 (00-99)
  • %Y : 네 자리 연도 표현 (0000-9999)
  • %m : 월 (01-12)
  • %d : 월 내 날짜 (01-31)
  • %H : 24시간 형식 시 (00-23)
  • %I : 12시간 형식 시 (01-12)
  • %M : 분 (00-59)
  • %S : 초 (00-59)
  • %a : 요일 약어
  • %A : 요일 전체명
  • %b : 월 약어
  • %B : 월 전체명
  • %c : 날짜 및 시간 전체 표현
  • %j : 연중 일수 (001-366)
  • %p : AM/PM 표시
  • %U : 연중 주차수 (00-53), 일요일 시작
  • %w : 요일 (0-6), 일요일 시작
  • %W : 연중 주차수 (00-53), 월요일 시작
  • %x : 지역 날짜 표현
  • %X : 지역 시간 표현
  • %Z : 현재 시간대 명칭
  • %% : 퍼센트 기호 자체

3. 달력 모듈 주요 함수

import calendar

# 주 시작 요일 설정 (0=월요일, 6=일요일)
calendar.setfirstweekday(6)

# 특정 월 달력 생성
single_month = calendar.month(2016, 1, w=2, l=1)

# 전체 연도 달력 생성
full_year_calendar = calendar.calendar(2019, w=2, l=1, c=6)

# 주 시작 요일 확인
start_day = calendar.firstweekday()

# 윤년 여부 판단
is_leap = calendar.isleap(2020)

# 지정 범위 내 윤년 수 계산
leap_count = calendar.leapdays(2019, 2020)

# 월별 요일 배열 반환
monthly_days = calendar.monthcalendar(2019, 1)

# 월의 범위 정보 (튜플) 반환
month_bounds = calendar.monthrange(2019, 4)

# 연간 달력 출력
display_year = calendar.prcal(2020)

# 월별 달력 출력
display_month = calendar.prmonth(2019, 12)

# time.gmtime 반대 기능: 시간 튜플 입력 후 타임스탬프 반환
# calendar.timegm(tuple_time)

# 지정 날짜의 요일 반환
day_of_week = calendar.weekday(2020, 6, 14)

4. 시간 모듈을 활용한 조회 시스템 구현

# 날짜 조회 시스템

import time
import calendar

running = True
timestamp_now = time.time()
local_time_data = time.localtime(timestamp_now)
formatted_current = time.strftime("%Y-%m-%d %H:%M:%S", local_time_data)

menu_prompt = """
조회 항목 선택:
   [1] 오늘 날짜 및 시간 조회
   [2] 특정 연도 속성 및 요일 수 조회
   [3] 연간 달력 출력
   [4] 종료

"""

while running:
    print(menu_prompt)
    selected_option = eval(input("선택: "))
    
    if selected_option == 2 or selected_option == 3:
        input_year = eval(input("연도 입력: "))
        input_month = eval(input("월 입력: "))
        input_day = eval(input("일 입력: "))

    if selected_option == 1:
        print(formatted_current)
    
    elif selected_option == 2:
        week_day_num = calendar.weekday(input_year, input_month, input_day) + 1
        is_leap_year = calendar.isleap(input_year)
        print(f"================요일 {week_day_num}")
        if is_leap_year:
            print("=============윤년")
        else:
            print("=============평년")

    elif selected_option == 3:
        print(calendar.month(input_year, input_month))

    elif selected_option == 4:
        running = False
        
    else:
        print("잘못된 입력입니다. 다시 시도해주세요!")

태그: python time Calendar datetime formatting

10월 7일 03:08에 게시됨