데이터분석

스탠다드 라이브러리에서 자주 사용 되는 모듈

개발하는지호 2024. 10. 17. 10:10
import random

 

 

randint()  함수

randint() 함수는 두 수 사이의 어떤 랜덤함 정수를 리턴하는 함수이다. randint(a, b) 를 하면, a <= N <= b 를 만족하는 어떤 랜덤한 정수 N을 리턴한다.

 

import random

print(random.randint(1, 20))
print(random.randint(1, 20))
print(random.randint(1, 20))
print(random.randint(1, 20))
print(random.randint(1, 20))

 

 

결과,

8
3
6
6
2

 

 

uniform()  함수

uniform() 함수는 두 수 사이의 랜덤한 소수를 리턴하는 함수이다. randint() 함수와 다른 것은 리턴하는 값이 정수가 아니라 소수라는 점이다. uniform(a, b) 를 하면, a <= N <= b 를 만족하는 어떤 랜덤한 소수 N을 리턴한다.

 

import random

print(random.uniform(0, 1))
print(random.uniform(0, 1))
print(random.uniform(0, 1))
print(random.uniform(0, 1))
print(random.uniform(0, 1))

 

 

결과,

0.08811632754196952
0.599056286966887
0.03005761564442677
0.45302183459579204
0.5120418463594933

 

 

 


 

import datetime

 

스탠다드 라이브러리에 있는 datetime 모듈은 '날짜'와 '시간'을 다루기 위한 다양한 '클래스'를 갖추고 있다.

 

datetime  값 생성

 

2020 3월 14일 파이썬으로 표현하면

pi_day = datetime.datetime(2020, 3, 14)
print(pi_day)
print(type(pi_day))




2020-03-14 00:00:00
<class 'datetime.datetime'>

 

이렇게 나타나고 시간은 자동으로 00시 00분 00초로 설정이된다. 

 

 

시간 역시 직접 설정이 가능하다.

pi_day = datetime.datetime(2020, 3, 14, 13, 6, 15)
print(pi_day)
print(type(pi_day))




2020-03-14 13:06:15
<class 'datetime.datetime'>

 

 

오늘 날짜

우리가 날짜와 시간을 정해주는게 아니라, 코드를 실행한 '지금 이 수간'의 날짜와 시간을 받아 올 수도 있다.

 

today = datetime.datetime.now()
print(today)
print(type(today))




2020-04-05 17:49:12.360266
<class 'datetime.datetime'>

 

 

timedelta 타입

두 datetime 값 사이의 기간을 알고 싶으면, 마치 숫자 뺄셈을 하듯이 그냥 빼면 된다.

 

today = datetime.datetime.now()
pi_day = datetime.datetime(2020, 3, 14, 13, 6, 15)
print(today - pi_day)
print(type(today - pi_day))



22 days, 4:42:57.360266
<class 'datetime.timedelta'>

 

이렇게 하면 결과값 타입이 'timedelta' 라는 타입으로 나온다. 이건 날짜 간의 차이를 나타내는 타입이라고 생각면 된다.

 

반대로 timedelta 를 생성해서 datetime 값에 더할 수도 있다.

 

today = datetime.datetime.now()
my_timedelta = datetime.timedelta(days=5, hours=3, minutes=10, seconds=50)

print(today)
print(today + my_timedelta)




2020-04-05 17:54:24.221660
2020-04-10 21:05:14.221660

 

 

datatime 해부하기

datetime 값에서 '연도'나 '월' 같은 값들을 추출하려면 

 

today = datetime.datetime.now()

print(today)
print(today.year)  # 연도
print(today.month)  # 월
print(today.day)  # 일
print(today.hour)  # 시
print(today.minute)  # 분
print(today.second)  # 초
print(today.microsecond)  # 마이크로초





2020-04-05 17:59:21.709817
2020
4
5
17
59
21
709817

 

 

datetime 포매팅

datetime 값을 출력하면 이쁜 형태로 나오지 않는다. 하지만 strftime() 함수를 사용하면, 우리 입맛대로 바꿀 수 있다.

 

today = datetime.datetime.now()

print(today)
print(today.strftime("%A, %B %dth %Y"))




2020-04-05 18:09:55.233501
Sunday, April 05th 2020

 

여기서 %A, %B, %d, %Y 와 같은 걸 포맷 코드라고 한다.

 

그 외에도 아래와 같이 다양한 포캣 코드가 있다.

 

 


 

 

 

비록 기본이지만 이렇게 한 번 작성해보면서 파이썬이 어떠한 코드인지 다시 한 번 되새겨 본다.

 

오늘도 좋은 공부였다~!