Python による日付と時刻の操作

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

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

はじめに

Python では、datetime モジュールが日付と時刻を扱うためのクラスを提供します。このモジュールのクラスの 1 つは date で、日付(年、月、日)を表し、日付を操作するためのさまざまなメソッドを提供します。もう 1 つのクラスは timedelta で、2 つの日付または時刻の期間または差分を表します。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/PythonStandardLibraryGroup -.-> python/date_time("Date and Time") subgraph Lab Skills python/comments -.-> lab-13613{{"Python による日付と時刻の操作"}} python/tuples -.-> lab-13613{{"Python による日付と時刻の操作"}} python/function_definition -.-> lab-13613{{"Python による日付と時刻の操作"}} python/importing_modules -.-> lab-13613{{"Python による日付と時刻の操作"}} python/using_packages -.-> lab-13613{{"Python による日付と時刻の操作"}} python/standard_libraries -.-> lab-13613{{"Python による日付と時刻の操作"}} python/date_time -.-> lab-13613{{"Python による日付と時刻の操作"}} end

何日か前

あなたの課題は、整数 n を引数として受け取り、今日から n 日前の日付を返す days_ago(n) という関数を書くことです。

この問題を解決するには、datetime モジュールの date クラスを使って現在の日付を取得し、timedelta クラスを使って現在の日付から n 日を引きます。

from datetime import timedelta, date

def days_ago(n):
  return date.today() - timedelta(n)
days_ago(5) ## date(2020, 10, 23)

まとめ

このチャレンジでは、datetime モジュールの datetimedelta クラスを使って、今日から n 日前の日付を計算する方法を学びました。Python で日付と時刻を扱う際に役立つスキルです。