728x90
파이썬에서 오늘 날짜를 가져오는 법
from datetime import datetime as dt
today = dt.now().date()
print(today)
-----------------------------------------
# 실행결과
2024-11-14
-----------------------------------------
형식을 지정해주는 법
- 기호
today = dt.now().strftime('%Y. %m. %d.')
print(today)
-----------------------------------------
# 실행결과
2024. 11. 14
-----------------------------------------
- 영어
today = dt.now().strftime('year: %Y month: %m day: %d')
print(today)
-----------------------------------------
# 실행결과
year: 2024 month: 11 day: 14
-----------------------------------------
- 한글
today = dt.now().strftime('%Y년 %m월 %d일')
print(today)
-----------------------------------------
# 실행결과
Traceback (most recent call last):
File "c:\Users\jeakwon\Desktop\workspace_docx\docx\take_in_request_form.py", line 7, in <module>
print(datetime.datetime.now().date().strftime('%Y년 %m월 %d일'))
UnicodeEncodeError: 'locale' codec can't encode character '\ub144' in position 2: encoding error
-----------------------------------------
에러가 뜬다.
해결방법
1. `strftime` 인풋 String을 유니코드 인코딩 후 디코딩
2. `strftime` 아웃풋 String을 인코딩 후 유니코드 디코딩
today = dt.now().strftime('%Y년 %d월 %m일.encode('unicode-escape').decode)
.encode().decode('unicode-escape')
-----------------------------------------
# 실행결과
2024년 11월 14일
-----------------------------------------
728x90
'Python' 카테고리의 다른 글
[Python] strftime과 strptime (0) | 2025.01.23 |
---|---|
[Python] 이메일에 파일 첨부하기 - smtplib (2) | 2024.11.19 |
[Python] UIAutomation for Windows 객체 컨트롤하기 (0) | 2024.10.22 |
[Python] Selenium으로 웹 브라우저 제어하기 - (1) (0) | 2024.10.18 |
[Python] Selenium 환경 설정 및 XPath의 이해 (3) | 2024.10.18 |