본문 바로가기
Python/개념익히기

모듈(datetime, time, urllib)

by ADELA_J 2023. 4. 11.

1. datetime 모듈 : 날짜와 시간 형식을 만들때 자주 사용되는 모듈

 

import datetime
print("#현재 시각 출력하기")
now = datetime.datetime.now()
print(now.year,"년")
print(now.month, "월")
print(now.day,"일")
print(now.hour, "시")
print(now.minute,"분")
print(now.second, "초")
print()

#시간 출력 방법
print("#시간을 포맷에 맞춰 출력하기")
output_a = now.strftime("%Y.%m.%d %H:%M:%S")
output_b = "{}{}{}{}{}{}초".format(now.year, now.month, now.day, now.hour, now.minute, now.second)
output_c = now.strftime("%Y{} %m{} %d{} %H{} %M{} %S {}"). format(*"년월일시분초")
print(output_a)
print(output_b)
print(output_c)
print()

     ▶output_a 처럼 strftime()함수를 사용하면 시간을 형식에 맞춰 출력 가능. 

     ▶timedelta ()함수를 사용하면 특정한 시간의 이전 또는 이후를 구할 수 있음.

         ▷ 1년 후를 구할땐 reploace()함수를 사용해 날짜 값을 교체하는 것이 보편적

 

2. time 모듈 : 시간 관련된 기능 다룰때

    ▶time.sleep() 함수는 특정 시간 동안 코드 진행을 정지할 때.

      ▷ 웹 크롤링을 할때 로딩시간이 있어서 대기 시간이 필요하므로 그때 사용하는 경우가 있음.

 

 

3. urllib 모듈 : url + library의 합성... ㅎ 인터넷 주소를 활용할 때 사용하는 라이브러리

 

     ▼잠깐 짚고 넘어가는 HTTP 프로토콜관련해서 내용

출처 : https://joshua1988.github.io/web-development/http-part1/   작성자 : Captain Pangyo  감사합니다.

             ▶ 브라우저(클라이언트)를 통해 HTTP Request(요청)을 받으면 서버가 소스를 찾아서 HTTP Response(응답)

             ▶ 항상 연결되어서 요청/응답이 오가는게 아니라 요청할때만 응답할때만 연결되고 끊어지는것.

 

#모듈을 읽어 들입니다.
from urllib import request

#urlopen()함수로 구글의 메인페이지를 읽습니다.
target = request.urlopen("https://google.com")
output = target.read()

#출력합니다.
print(output)