251112_BootCamp Day 18_파이썬 라이브러리
2025. 11. 12. 20:34ㆍTIL
1. datetime 라이브러리
datetime 라이브러리는 시간 데이터를 다뤄야 할 때 사용할 수 있는 라이브러리이다.
날짜 단위의 계산을 해야 되는 경우(ex. 특정 일자를 기준으로 N일을 더한다) 반드시 날짜형 데이터를 이용해 계산해야 하기 때문에, 문자열을 날짜로 바꿔 주어야 한다. 또한 출력할 때 포맷 상의 문제로 문자 형태로 출력해야 하는 경우도 날짜형 데이터를 문자열로 바꿀 수 있다.
import datetime
# 현재 날짜와 시간
now = datetime.datetime.now()
print(f"Current date and time : {now}")
# 특정 날짜 생성
some_date = datetime.date(2025, 4, 3)
print(f"Specific date : {some_date}")
# 특정 시간 생성
some_time = datetime.time(12, 8, 30)
print(f"Specific time : {some_time}")
# 날짜와 시간 간격 계산
two_days_later = now + datetime.timedelta(days=2)
print(f"Two days from now : {two_days_later}")
# 날짜 포맷팅
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time : {formatted_date}")
# 문자열로부터 날짜 파싱
date_from_string = datetime.datetime.strptime("2024-01-15", "%Y-%m-%d")
print(f"Parsed date from string : {date_from_string}")

2. math 라이브러리
math 라이브러리는 다양한 수학 계산을 할 수 있는 함수들을 제공한다. 제곱이나 팩토리얼, 최대공약수 같은 계산은 파이썬 코드로도 구현이 가능하지만, 코드가 길어지고 함수를 추가해야 한다는 단점이 있기 때문에 math 라이브러리의 함수들을 이용하면 여러 수학적 계산을 쉽게 파이썬에서 구현할 수 있다.
import math
# 제곱근 계산
num_sqrt = math.sqrt(16)
print(f"Square root of 16 = {num_sqrt}")
# 제곱 계산
num_power = math.pow(3, 4)
print(f"Power of 3 to 4 = {num_power}")
# 팩토리얼 계산
num_factorial = math.factorial(10)
print(f"Factorial of 10 = {num_factorial}")
# 최대공약수 계산
num_gcd = math.gcd(36, 24)
print(f"GCD of 36 and 24 = {num_gcd}")
# 라디안(radian) <-> 각도(degrees) 변환
radian = math.radians(180)
print(f"Raidan of 180 degree is {radian}")
degree = math.degrees(math.pi)
print(f"Degree of pi is {degree}")
# 삼각함수 계산 (라디안 값 기준)
angle = math.radians(90)
sin = math.sin(angle)
cos = math.cos(angle)
tan = math.tan(angle)
print(f"Angle = pi/2, sin = {sin}, cos = {cos}, tan = {tan}")
# 로그 함수 계산
ln = math.log(10)
log2 = math.log(10, 2)
log10 = math.log10(10)
print(f"ln of 10 = {ln}, log2 of 10 = {log2}, log10 of 10 = {log10} ")
# 지수 함수 계산
exp2 = math.exp(2)
# 부동소수 비교
# 부동소수점 : 실수(float)를 컴퓨터상에서 근사하여 표현할 때, 소수점 위치를 고정하지 않고
# 그 위치를 나타내는 수를 따로 적는 것.
# 유효숫자를 나타내는 가수와, 소수점 위치를 풀이하는 지수로 나누어 표현한다.
a = 0.1 + 0.2
print(math.isclose(a, 0.3, rel_tol = 1e-9))

3. random 라이브러리
random 라이브러리는 무작위 수가 필요할 때 사용할 수 있는 라이브러리이다.
특정 범위 내에서 난수를 하나씩 뽑아낼 수 있으며, 시퀀스 데이터(리스트, 딕셔너리 등)에서도 임의의 값을 가져오거나, 순서를 랜덤하게 섞거나, 특정 값에 가중치를 두는 방식으로 무작위 추출을 하게 할 수 있다.
import random
# 0.0 ~ 1.0 사이 임의의 수
rand1 = random.random()
print(f"Random number between 0.0 and 1.0: {rand1}")
# 특정 범위의 임의의 정수
rand2 = random.randint(1, 10)
print(f"Random int between 1 and 10 : {rand2}")
# 시퀀스에서 추출
grades = ['A', 'B', 'C', 'D', 'E']
rand_grade = random.choice(grades)
print(f"Random grade : {rand_grade}")
print(f"Random 2 grades : {random.sample(grades, 2)}")
# 시퀀스 순서 섞기
random.shuffle(grades)
print(f"Shuffled sequence : {grades}")
# 가중치 추출
weight = [10, 20, 30]
print(f"Random weight = {random.choices(weight, weights=[1, 5, 1], k=3)}")

'TIL' 카테고리의 다른 글
| 251114_BootCamp Day 20_QGIS를 이용한 공간 데이터 분석 (0) | 2025.11.14 |
|---|---|
| 251113_BootCamp Day 19_파이썬(기초) 마무리 (2) | 2025.11.13 |
| 251111_BootCamp Day 17_컴프리헨션, 예외처리 (0) | 2025.11.11 |
| 2511110_BootCamp Day 16_EDA (1) | 2025.11.10 |
| 251107_BootCamp Day 15_3주차 회고 (2) | 2025.11.07 |