파이썬 모듈 #9

반영환·2023년 4월 29일

파이썬

목록 보기
9/17
post-thumbnail

파이썬 모듈

한 파일에.. 함수도 있고.. 실행 코드도 있으면... 많이 더러울거야 그치?

사칙연산 함수만 모아놓은 파일이 있다고 하자.

def add(num1, num2):
	return num1 + num2
    
def subtract(num1, num2):
	return num1 - num2
    
def multiply(num1, num2):
	return num1 * num2
    
def division(num1, num2):
	return num1 / num2

위의 파일 이름을 calculator.py라 하면, 이를 우리가 run.py 파일에서 사용하고 싶을 때!

import calculator

print(calculator.add(2,3)) # 5
print(calculator.multiply(2,3)) # 6
# import 키워드를 이용해서 파일을 불러올 수 있다!

다른 경로의 파일을 import 하고 싶을 때

하위 경로

-folder1
--aaa.py
--floder2
---bbb.py

# aaa.py에서 bbb.py 불러오기
from folder2 import bbb

# 폴더를 패키지라 생각하면 된다.​

상위 경로

-folder1
--aaa.py
--floder2
---bbb.py

# bbb.py에서 aaa.py 불러오기
import sys, os
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
# 절대 경로를 참조하는 코드

import aaa​

같은 경로의 하위 폴더

-folder1
--aaa.py
--folder2
---bbb.py
--floder3
---ccc.py

# ccc.py에서 bbb.py를 불러오고 싶을 때


import sys, os
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
# 절대 경로를 참조하는 코드

from folder2 import ddd

#출처 : https://freedata.tistory.com/70

모듈의 이름 변경하기

as

import calculator as calc

모듈에서 메소드 몇 개만 가져오기

from [Package(File)name] import [Method]

 

from calculator import add, multiply

print(add(2,3))
# cf print(calculator.add(2,3))

파이썬 스탠다드 라이브러리

스탠다드 라이브러리란 개발자들이 쓸만한 기능들을 미리 만들어 놓은 것이다.

여러 종류가 있지만 간단하게 살펴보자.

math 모듈

수학적 기능을 사용할 수 있게 해주는 라이브러리.

log, cos, sin, pi 등의 수학함수나 상수를 불러올 수 있다.

random 모듈

랜덤한 숫자를 생성하기 위한 다양한 함수를 제공해주는 라이브러리.

random.random()

:> random한 0~1사이 숫자가 나온다.

random.randint(a, b)

:> 두 수 a, b 사이의 어떠한 랜덤한 정수를 리턴

randint(a, b) # a<= N <= b를 만족하는 랜덤한 정수 N을 리턴

import random

print(random.randint(1, 20))
# 13​

random.uniform(a, b)

:> 두 수 a, b 사이의 랜덤한 소수를 리턴하는 함수.

uniform(a, b) # a<= N <= b를 만족하는 랜덤한 소수 N을 리턴

import random

print(random.uniform(0, 1))

#0.59213185432​

datetime 모듈

datetime 모듈은 '날짜'와 '시간'을 다루기 위한 다양한 '클래스'를 가지고 있다!

datetime 값 생성

1999년 8월 16일을 표현해보자.

import datetime

hwany_day = datetime.datetime(1999, 8, 16)
print(hwany_day) # 1999-08-16 00:00:00
print(type(hwany_day)) # <class 'datetime.datetime'>​
 

값 생성시 시간은 자동으로 00시 00분 00초로 설정됨.

시간도 설정하고 싶다면!

import datetime

hwany_day = datetime.datetime(1999, 8, 16, 13, 15, 20)
print(hwany_day) # 1999-08-16 13:15:20
print(type(hwany_day)) # <class 'datetime.datetime'>​​
 

오늘의 날짜 받아오기

코드를 실행한 지금 이 순간의 날짜와 시간을 받아오려면

today = datetime.datetime.now()
print(today) # 2020-04-05 17:49:12.360266
print(type(today)) # <class 'datetime.datetime'>​

timedelta

두 datatime 값 사이 기간을 알고 싶으면, 숫자 빼듯이 빼주면 된다.

today = datetime.datetime.now()
hwany_day = datetime.datetime(1999, 8, 16, 13, 6, 15)
print(today - hwany_day) 
print(type(today - hwany_day)) # <class 'datetime.timedelta'>​

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

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

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

datetime 포멧팅

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와 같은 걸 포맷 코드라고 한다.

###포멧코드###
%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

OS모듈

우리가 os를 파이썬에서 제어할 수 있도록 도와주는 모듈이다.

os.getlogin() # 현재 로그인 계정을 불러줌
os.getcwd() # 현재 파일이 있는 폴더 경로를 가져옴
 

2021-09-13

profile
최고의 오늘을 꿈꾸는 개발자

0개의 댓글