프롬프트 없음
datetime 모듈은 날짜와 시간에 관련된 데이터를 다루기 위해 파이썬에서 제공하는 내장 모듈입니다. 이 모듈을 사용하면 날짜 및 시간의 계산, 포맷팅, 비교 등을 쉽게 수행할 수 있습니다. datetime 모듈의 주요 클래스는 다음과 같습니다:
이제 각 클래스의 주요 메서드를 살펴보며 실습해보겠습니다.
from datetime import datetime
# 현재 날짜와 시간 가져오기
now = datetime.now()
print("현재 날짜와 시간:", now)
# 특정 날짜와 시간 생성
specific_date = datetime(2023, 10, 1, 15, 30)
print("특정 날짜와 시간:", specific_date)
# 날짜와 시간 포맷팅
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("포맷팅된 날짜와 시간:", formatted_date)
from datetime import date
# 현재 날짜 가져오기
today = date.today()
print("오늘의 날짜:", today)
# 특정 날짜 생성
specific_date = date(2023, 10, 1)
print("특정 날짜:", specific_date)
# 날짜의 연도, 월, 일 추출
year = today.year
month = today.month
day = today.day
print(f"오늘 날짜의 연도: {year}, 월: {month}, 일: {day}")
from datetime import time
# 특정 시간 생성
specific_time = time(15, 30, 45)
print("특정 시간:", specific_time)
# 시간의 시, 분, 초 추출
hour = specific_time.hour
minute = specific_time.minute
second = specific_time.second
print(f"시간 정보 - 시: {hour}, 분: {minute}, 초: {second}")
from datetime import timedelta
# timedelta 객체 생성 (일 단위)
delta = timedelta(days=5)
print("5일 후:", datetime.now() + delta)
# 두 날짜 간의 차이 계산
date1 = date(2023, 10, 1)
date2 = date(2023, 10, 10)
difference = date2 - date1
print("날짜 차이:", difference.days, "일")
from datetime import datetime, timezone, timedelta
# UTC 시간대 생성
utc_time = datetime.now(timezone.utc)
print("UTC 시간:", utc_time)
# 특정 시간대 생성 (UTC+9, 한국 표준시)
korea_timezone = timezone(timedelta(hours=9))
korea_time = datetime.now(korea_timezone)
print("한국 시간:", korea_time)
이 실습 자료를 통해 datetime 모듈의 주요 클래스와 메서드를 이해하고 활용하는 방법을 익힐 수 있습니다. 실습을 통해 얻은 지식을 바탕으로 날짜와 시간 관련 기능을 구현해보세요!