Python の日付と時間

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、19世紀のビクトリア時代の世界に足を踏み入れます。そこでは、謎めいた時間関連の手がかりを巡る不可解な事件を解明するために、謎の探偵が任務に励んでいます。この時代の雰囲気は、神秘とエレガンスに包まれており、私たちの取り組みの舞台を築いています。この探偵は、鋭い観察力と演繹的な推理力で知られており、Pythonの日付と時間の機能を活用して、調査中の事件に隠されたメッセージを解読しなければなりません。


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

時刻データで舞台を設定する

このステップでは、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の日付と時間の機能を探究しました。時間データの操作と変換を習得することで、探偵は謎めいた時間関連の手がかりを解明するための技術を磨き、最終的にはこの謎めいた事件の解決につながりました。