Python 日期与时间

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

Introduction

In this lab, we will step into the world of a 19th-century Victorian era, where a mysterious detective is on a mission to unravel a perplexing case involving cryptic time-related clues. The ambiance of this era, shrouded in mystery and elegance, sets the stage for our endeavor. The detective, known for their astute observational skills and deductive reasoning, must leverage Python's date and time capabilities to decipher the hidden messages in the case they are investigating.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/PythonStandardLibraryGroup -.-> python/date_time("Date and Time") subgraph Lab Skills python/date_time -.-> lab-271543{{"Python 日期与时间"}} end

Setting the Stage with Time Data

In this step, we will start by creating a Python script to retrieve and display the current date and time. The detective will use this script to verify the timeline of events and establish critical reference points for their investigation.

In ~/project/display_time.py:

## File: ~/project/display_time.py

import datetime

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

Run the script:

python display_time.py

The information below should be displayed on your terminal:

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 的日期和时间功能,以帮助一位神秘的侦探解决一个发生在维多利亚时代的复杂案件。通过掌握时间数据的操作和转换,侦探提升了他们解码与时间相关的神秘线索的能力,最终成功破解了这个谜团。