34. 파이썬 - random, datetime module

2024. 7. 11. 13:133층 1구역 - 개발의 장/Python 프로그래밍 핵심 개념

1. 서론

간단하게 모듈 몇가지를 알아봤는데

random과 datetime에 대해서도 알아보자.

 

2. 본론

2-1. random

2-1-1. random.randint(a, b)

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))

 

1 이상 20 이하의 숫자 5개를 출력한다.

아마 출력할 때마다 매번 다른 수가 출력될 것이다.

 

2-1-2. random.uniform(a, b)

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 이상 1 이하의 소수 5개를 출력한다.

아마 출력할 때마다 매번 다른 소수가 출력될 것이다.

 

2-2. datetime

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

import datetime

 

2020년 3월 14일을 파이썬으로 어떻게 표현할 수 있을까?

 

2-2-1. datetime.datetime()

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

 

 

결과를 보면 시간에 대해서 자동으로 00시 00분 00초로 설정되었다.

이 시간도 직접 정할 수 있다.

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

 

2-2-2. datetime.datetime.now()

오늘 날짜, 우리가 날짜와 시간을 정해 주는 게 아니라, 코드를 실행한

'지금 이 순간' 의 날짜와 시간을 받아올 수 있다.

 

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

 

 

2-2-3. 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))

 

 

위 결과에 2가지의 datetime을 빼면, 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)

 

 

2-2-4. datetime 해부하기

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)  # 마이크로초

 

 

2-2-5. datetime 포매팅

datetime 값을 좀 더 이쁘게 바꿀 수 있는 방법도 있다.

strftime() 함수를 사용하면 된다.

today = datetime.datetime.now()

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

 

 

%A, %B, %d, %Y와 같은 것들을 포맷 코드라고 한다.

 

포맷코드 설명
%a 요일 (짧은 버전)  Mon
%A 요일 (풀 버전) Monday
%w                                      요일 (숫자 버전, 0~6, 0이 일요일)  5
%d                                                          일 (01~31)  23
%b                                                       월 (짧은 버전) Nov
%B                                                           월 (풀 버전) November
%m                                                   월 (숫자 버전, 01~12) 10
%y                                                       연도 (짧은 버전) 16
%Y                                                       연도 (풀 버전) 2016

 

%H                                                           시간 (00~23) 14
%I                                                           시간 (00~12) 10
%p                                                              AM/PM  AM
%M                                                           분 (00~59) 34
%S                                                           초 (00~59) 12
%f                      마이크로초 (000000~999999)        413215
%Z                                                           표준시간대 PST
%j                                           1년 중 며칠째인지 (001~366) 162
%U               1년 중 몇 주째인지 (00~53, 일요일이 한 주의 시작이라고 가정) 35
%W              1년 중 몇 주째인지 (00~53, 월요일이 한 주의 시작이라고 가정)  35

3. 결론