[파이썬300제] 241~250 정리

·2023년 10월 16일

Python 300

목록 보기
4/5
post-thumbnail

WikiDocs : 초보자를 위한 파이썬 300제 풀면서 학습한 내용 정리 (참고 : https://wikidocs.net/book/922)

1. 파이썬 모듈

  • 프로그램이 길어지면 여러 함수와 변수들이 생기는데 자주 사용하는 함수와 변수들을 따로 script로 만들어서 저장해두면 프로그램을 만들때, 필요할때마다 꺼내서 쓸수 있어서 프로그램 안에 일일이 작성하지 않아도 되서 유지 보수에 효율적이다.
    • 함수, 변수, 클래스 등의 코드를 모아둔 파일을 모듈이라고 부른다.
      • 모듈을 사용할때 : import module_name
      • 모듈안에 정의된 이름을 보고싶을때 : dir(module_name) ; dir() function
      • 모듈 안에 있는 함수 정의 확인 : help(module_name.function_name)
        # datetime 모듈
        import datetime
        
        dir(datetime)
        help(datetime.timedelta)

2. Python Interpreter

  • 파이썬 프로그램을 실행하는데 사용되는 소프트웨어
    • 파이썬은 대화식 프로그래밍 언어
      • 대화식 프로그래밍 언어
        - 코드를 입력하고 바로 실행해보고 결과를 확인할수 있는 프로그래밍언어(e.g. 파이썬)
      • 컴파일러언어
        - 코드를 작성하고 컴파일러를 사용해서 코드를 컴파일하고 실행파일을 생성하고 그 실행파일을 실행해서 결과를 확인하는 프로그래밍 언어 (e.g. C언어)
        - 컴파일러(일반적으로 gcc)가 컴파일할때 코드의 잠재문제를 식별하고 이를 오류로 띄워주기떄문에 실행 파일이 생성되기 전에 코드의 정확성을 확인할수 있음
        - 바로 결과값을 확인하지는 못하기때문에 대화식 언어보다 개발 속도가 느림
    • 즉시 코드를 입력하고 실행할수 있음
    • 파이썬 표준 라이브러리, 모듈을 사용할수 있도록 지원함
      • 주피터노트북: 파이썬 인터프리터를 포함한 대화식 프로그래밍 환경

3. datetime 모듈의 timedelta class

| A timedelta object represents a duration, the difference between two dates or times.

  • 날짜나 시간과 관련해 계산을 해야할때 유용함

    now = datetime.datetime.now()
    delta = datetime.timedelta(days=5)
    # timedelta로 5일 duration을 만들고,
    
    day_before_5 = now - delta
    # 이렇게 datetime을 이용해 연산계산을 해서 특정 날짜나 시간 값을 얻어낼때 사용함
    
    print(now, "/", day_before_5)
    
    #... 2023-10-12 22:34:06.821551 / 2023-10-07 22:34:06.821551

4. Naive Objects / Aware Objects

  • Naive Objects : time zone 에 대한 정보 X
  • Aware Objects: time zone 정보 O
    • datetime.datetime.now() returns an aware datetime object.
    • The now() function, when called without any arguments, returns a datetime object with the local time zone information.

5. strftime() method

6. datetime.strptime() method

  • datetime.strptime(date_string, format)

    • the datetime.strptime() class method creates a datetime object from a string representing a date and time and a corresponding format string.
    		import datetime
    		strptime = datetime.datetime.strptime("2023-10-13", "%Y-%m-%d")
     
    		print(strptime, type(strptime))
    		#... 2023-10-13 00:00:00 <class 'datetime.datetime'>
    		```

7. sleep() function

  • time.**sleep**(secs)
  • Suspend execution of the current thread for the given number of seconds.
  • 지정한 시간(초)만큼 프로그램을 멈추게한다 → 그래서 sleep함수
    import time
    
    # Delay for 5 seconds
    time.sleep(5)
    
    # Display a message after the delay
    print("Delayed message after 5 seconds")

8. 모듈 임포트하는 방법

    # import the entire module
    import time
    
    # import with an alias
    import time as t
    
    # import specific itemes : can use specific fuctinos or variable 
    from time import sleep
    
    sleep(10)
    print("Hello")
    
    # import everything(not recommended) 
    #	: can use them directly without the module name prefix
    #	: may lead to naming conflicts if multiple modules have the same names
    from time import *

9. os module

  • os.getcwd() : 현재의 디렉토리 경로를 리턴
  • os.rename(”파일경로/파일이름”, “파일경로/바꿀파일이름”) : 파일이름 변경
    • 파일경로를 바꿀수는 없음
       # 만약 파일경로를 바꿔서 새로운 이름으로 저장하고 싶으면
       import os
       import shutil
       
       source_file = "/Users/seul/Desktop/test.txt"
       destination_directory = os.getcwd()  # Current working directory
       new_filename = "after.txt"
       
       # Combine the destination directory and new filename
       destination_path = os.path.join(destination_directory, new_filename)
       
       # Move the file to the new directory and rename it
       shutil.move(source_file, destination_path)

10. numpy module

  • numpy.arange([start, ]stop, [step, ]dtype=None, *like=None)
    - Return evenly spaced values within a given interval
    - including start but excluding stop
    → array로 리턴함!**
profile
사랑을담아봄

0개의 댓글