【Python入門】Pythonのdatetimeモジュールとは?使い方と活用方法を徹底解説

Python

Pythonのdatetimeモジュールは、Pythonの標準ライブラリのひとつであり、日付、時間、および時間の間の操作を行うためのモジュールです。この記事ではこのモジュールを使用して、初心者向けに日付と時刻を操作する方法について説明していきます。

# Datetimeオブジェクトの作成(現時点における日時の参照)
CURRENT = datetime.datetime.now()
# Datetimeオブジェクトの作成(特定の日時の指定)
NEW = datetime.datetime(YEAR, MONTH, DAY)
# Datetimeオブジェクトによる日時の計算
NEW = DATETIME + datetime.timedelta(DAY)
# Datetimeオブジェクトによる経過日時の計算
PASS = DATETIME(After) - DATETIME(Before)

下記の様な内容で悩んでいる/困っている場合に使える方法を参考までにご共有させて頂きます。

・Pythonには、どのモジュールを使って時間や日時を扱うの?
・Pythonのdatetimeモジュールは、どの様に使うのだろうか?

Datetimeオブジェクトの作成

Datetimeオブジェクトの作成(現時点における日時の参照)

現時点における日時の参照をするDatetimeオブジェクトを作成するには、datetimeモジュールをインポートし、以下のようにコードを書きます。

import datetime

current_info = datetime.datetime.now()
print(current_info)
2023-03-11 22:11:37.816693

上記のプログラムは、現在の日付と時間を取得し、current_infoに格納します。Datetimeオブジェクトには、年、月、日、時、分、秒、マイクロ秒など、さまざまな属性があります。これらは、以下のようにアクセスできます。

import datetime

current_info = datetime.datetime.now()

info_Y = current_info .year
info_M = current_info .month
info_D = current_info .day
info_h = current_info .hour
info_m = current_info .minute
info_s = current_info .second
info_mic = current_info .microsecond

print(f"{info_Y}年{info_M}月{info_D}日 {info_h}時{info_m}分{info_s}秒{info_mic}マイクロ秒")
2023年3月11日 22時17分9秒548854マイクロ秒

Datetimeオブジェクトの作成(特定の日時の指定)

Datetimeオブジェクトを作成する際に、年、月、日、時、分、秒、マイクロ秒などの値を指定することもできます。例えば、以下のようにコードを書くことで、2023年1月1日のDatetimeオブジェクトを作成することができます。

import datetime

new_year = datetime.datetime(2023, 1, 1)

print(new_year)
2023-01-01 00:00:00

Datetimeオブジェクトの表示

Datetimeオブジェクトを表示するときに、フォーマットを指定することができます。例えば、日付を「月 日 年 曜日」の形式で表示するには、以下のようにコードを書きます。

import datetime

current_info = datetime.datetime.now()

print(current_info.strftime("%B %d %Y (%a)"))
March 11 2023 (Sat)

Datetimeオブジェクトの操作

Datetimeオブジェクトは、算術演算が可能です。例えば、ある特定の日時から一週間後の日時を計算するには、以下のようにコードを書きます。

import datetime

current = datetime.datetime.now()
next = current + datetime.timedelta(days=7)

print(current)
print(next)
2023-03-11 22:30:18.909080
2023-03-18 22:30:18.909080

Datetimeオブジェクトには、他にも様々な演算を行うことができます。例えば、2つのDatetimeオブジェクトの差分を計算することで、以下の様に正月から現時点までの経過日時を計算することもできます。

import datetime

current = datetime.datetime.now()
new_year = datetime.datetime(2023, 1, 1)

print(current - new_year)
69 days, 22:32:57.979170

まとめ

Pythonのdatetimeモジュールは、日付と時刻の操作に便利な機能を提供しています。この記事で説明した基本的な機能を使って、自分のプロジェクトで日付と時刻を操作してみてください。

関連検索ワード

How to use python “datetime” module?
How to use python “datetime” library?

関連キーワード

python, 入門, 使い方, 初心者, datetime, module

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny