08_00. (P)날짜 다루기와 문자열 다루기
파이썬에서 날짜와 문자를 다루는 방법에 대해 각각 설명드리겠습니다. ## 1. 날짜 다루기 (Date Handling) 파이썬에서 날짜 및 시간을 다루는 주요 모듈은 datet…
wikidocs.net
파이썬에서 날짜와 문자를 다루는 방법에 대해 각각 설명드리겠습니다.
## 1. 날짜 다루기 (Date Handling)
파이썬에서 날짜 및 시간을 다루는 주요 모듈은 datetime입니다. 이 모듈을 사용하면 날짜와 시간을 쉽게 처리할 수 있습니다.
### 1.1. 현재 날짜 및 시간 가져오기
from datetime import datetime
# 현재 날짜와 시간 가져오기
now = datetime.now()
print(now)
#### 1.2. 특정 날짜 객체 생성
from datetime import datetime
# 특정 날짜와 시간 생성 (2024년 9월 16일, 오후 3시 30분)
specific_date = datetime(2024, 9, 16, 15, 30)
print(specific_date)
#### 1.3. 날짜에서 년, 월, 일 추출
now = datetime.now()
year = now.year
month = now.month
day = now.day
print(f"Year: {year}, Month: {month}, Day: {day}")
#### 1.4. 날짜 형식 변경 (문자열 변환)
#날짜를 문자열로 변환하거나, 문자열에서 날짜 객체를 생성할 때 strftime() 및 strptime() 메서드를 사용합니다.
#strftime(): 날짜를 특정 형식의 문자열로 변환
#strptime(): 문자열을 특정 형식의 날짜로 변환
from datetime import datetime
# 현재 날짜를 문자열로 변환
now = datetime.now()
date_str = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Date as string: {date_str}")
# 문자열을 날짜로 변환
date_from_str = datetime.strptime("2024-09-16", "%Y-%m-%d")
print(f"Date from string: {date_from_str}")
#### 1.5. 날짜 간 차이 계산
# timedelta 객체를 사용하여 날짜 간의 차이를 계산할 수 있습니다.
from datetime import datetime, timedelta
# 현재 날짜
now = datetime.now()
# 10일 후의 날짜 계산
future_date = now + timedelta(days=10)
print(f"10 days from now: {future_date}")
# 날짜 차이 계산
date_diff = future_date - now
print(f"Difference in days: {date_diff.days}")
## 2. 문자 다루기 (String Handling)
파이썬에서 문자열은 str 타입으로 다룹니다. 문자열을 다루는 다양한 내장 함수와 메서드들이 있습니다.
#### 2.1. 문자열 생성 및 기본 조작
# 문자열 생성
text = "Hello, World!"
# 문자열의 길이 확인
print(len(text))
# 문자열의 일부 추출 (슬라이싱)
print(text[0:5]) # "Hello"
#### 2.2. 문자열 합치기 (Concatenation)
여러 문자열을 합칠 때 + 연산자 또는 join() 메서드를 사용할 수 있습니다.
# 문자열 합치기
greeting = "Hello" + ", " + "World!"
print(greeting)
# join()을 사용한 문자열 합치기
words = ["Hello", "World", "!"]
sentence = " ".join(words)
print(sentence)
#### 2.3. 문자열 분리 (Splitting)
# 문자열을 특정 구분자를 기준으로 분리할 수 있습니다.
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits) # ['apple', 'banana', 'orange']
#### 2.4. 문자열 대소문자 변환
#lower(): 모든 문자를 소문자로 변환
#upper(): 모든 문자를 대문자로 변환
#capitalize(): 첫 문자를 대문자로 변환
text = "Hello World"
# 소문자로 변환
print(text.lower()) # "hello world"
# 대문자로 변환
print(text.upper()) # "HELLO WORLD"
#### 2.5. 문자열 검색 및 치환
#find(): 문자열 내에서 특정 문자의 위치 찾기
#replace(): 문자열 내 특정 문자를 다른 문자로 교체
text = "Hello World"
# 특정 문자 위치 찾기
index = text.find("World")
print(f"World starts at index: {index}")
# 특정 문자 교체
new_text = text.replace("World", "Python")
print(new_text) # "Hello Python"
#### 2.6. 문자열 형식화 (String Formatting)
#문자열 내에서 값을 삽입하거나 형식을 맞출 때 format() 메서드나 f-string을 사용할 수 있습니다.
# format() 사용
greeting = "Hello, {}!".format("Taeyong")
print(greeting)
# f-string 사용 (Python 3.6 이상)
name = "Taeyong"
greeting = f"Hello, {name}!"
print(greeting)
## 요약
날짜 다루기: datetime 모듈로 날짜와 시간을 쉽게 처리하고, timedelta로 날짜 간 차이를 계산할 수 있습니다.
문자 다루기: 문자열은 파이썬에서 str 타입으로 다루며, 다양한 메서드로 변환, 조작, 검색, 치환 등을 할 수 있습니다.
이러한 기능들을 조합하면 날짜와 문자 데이터를 효과적으로 처리할 수 있습니다.