Python 날짜 및 시간

PythonBeginner
지금 연습하기

소개

이번 랩에서는 19 세기 빅토리아 시대의 세계로 들어가, 수수께끼 같은 시간 관련 단서를 풀기 위해 임무를 수행하는 미스터리한 탐정을 만나보겠습니다. 미스터리와 우아함으로 뒤덮인 이 시대의 분위기는 우리의 노력을 위한 무대를 설정합니다. 예리한 관찰력과 추론 능력을 갖춘 것으로 알려진 탐정은 Python 의 날짜 및 시간 기능을 활용하여 조사 중인 사건의 숨겨진 메시지를 해독해야 합니다.

시간 데이터로 무대 설정

이 단계에서는 현재 날짜와 시간을 검색하고 표시하는 Python 스크립트를 생성하는 것으로 시작합니다. 탐정은 이 스크립트를 사용하여 사건의 타임라인을 확인하고 조사에 필요한 중요한 기준점을 설정합니다.

~/project/display_time.py에서:

## File: ~/project/display_time.py

import datetime

current_time = datetime.datetime.now()
print("Current date and time:", current_time)

스크립트 실행:

python display_time.py

다음 정보가 터미널에 표시되어야 합니다:

Current date and time: 2024-01-17 18:54:37.798326

단서 분석을 위한 시간 조작

이 단계에서는 탐정의 스크립트를 개선하여 시간 데이터를 조작합니다. Python 의 datetime 모듈을 사용하여 시간 간격을 빼고 더하여 사건에 중요한 시간 관련 단서를 해독하는 과정을 시뮬레이션합니다.

~/project/time_manipulation.py에서:

## File: ~/project/time_manipulation.py

import datetime

current_time = datetime.datetime.now()
print("Current date and time:", current_time)

## Subtracting 5 days from current time
new_time = current_time - datetime.timedelta(days=5)
print("Time 5 days ago:", new_time)

## Adding 3 hours to the current time
new_time = current_time + datetime.timedelta(hours=3)
print("Time 3 hours later:", new_time)

스크립트 실행:

python time_manipulation.py

다음 정보가 터미널에 표시되어야 합니다:

Current date and time: 2024-01-17 18:55:36.077424
Time 5 days ago: 2024-01-12 18:55:36.077424
Time 3 hours later: 2024-01-17 21:55:36.077424

단서 해독을 위한 시간 형식 변환

이 단계에서 탐정은 스크립트를 확장하여 시간 데이터를 다양한 형식으로 변환합니다. 이는 조사 중에 마주치는 다양한 시간 관련 단서를 해독하는 데 필수적입니다.

~/project/time_conversion.py에서:

## File: ~/project/time_conversion.py

import datetime

current_time = datetime.datetime.now()
print("Current date and time (ISO format):", current_time.isoformat())

## Converting time to a custom format
custom_format = current_time.strftime("%Y-%m-%d %H:%M:%S")
print("Current date and time (custom format):", custom_format)

스크립트 실행:

python time_conversion.py

다음 정보가 터미널에 표시되어야 합니다:

Current date and time (ISO format): 2024-01-17T18:57:11.001163
Current date and time (custom format): 2024-01-17 18:57:11

요약

이 랩에서는 Python 의 날짜 및 시간 기능을 탐구하여 빅토리아 시대에 설정된 난해한 사건을 해결하는 데 도움을 주는 신비한 탐정을 도왔습니다. 시간 데이터의 조작 및 변환을 마스터함으로써 탐정은 암호 같은 시간 관련 단서를 풀기 위한 기술을 연마하여 궁극적으로 수수께끼 같은 사건을 해결했습니다.