クラスオブジェクトを使ってみよう-その2

記事の内容

 この記事では、クラスオブジェクトの使用例として、datetimeモジュールのdatetimeクラスの使い方を説明します。「オブジェクトって何だろう?」という方は、先にオブジェクト、クラスの基本の記事を読むことをお勧めします。

***わからない用語があるときは索引ページへ***

1.datetimeクラスの紹介

 datetimeモジュールのdatetimeクラスを使うと、現在時刻を取得したり、日時計算が簡単にできたりします。

ややこしいですがdatetimeクラスはモジュールと名前が同じです。
datetimeモジュールも標準ライブラリで提供されているモジュールです。

2.datetimeクラスのサンプルプログラム

 サンプルプログラムの動きを見てみましょう。記事の後ろでサンプルプログラムの動きを1つ1ずつ説明しています。

##datetime_ex1.py

##datetimeクラスのインポート
from datetime import datetime

##datetimeクラスのクラスメソッドnow()を使って、
##インスタンスを生成することなくdatetimeクラスから直接現在の日時を取得する
##now()はクラスから直接呼び出すことができる
print("datetimeのクラスメソッドnow()")
current_datetime = datetime.now()
print("current_time:", current_datetime)

##current_timeのクラスを確認してみると、datetimeクラスの
##インスタンスであることがわかる
print("current_timeのクラス:", type(current_datetime))
print("\n")

##curent_timeインスタンスを使って、datetimeクラスの主なクラス属性(プロパティ)をのぞいてみる
print("datetimeクラスのクラス属性(プロパティ)")
print("year:", current_datetime.year)
print("month:", current_datetime.month)
print("day:", current_datetime.day)
print("hour:", current_datetime.hour)
print("minute:", current_datetime.minute)
print("second:", current_datetime.second)
print("millisecond:", current_datetime.millisecond)
print("microsecond:", current_datetime.microsecond)
print("timezone:", current_datetime.tzinfo)
print("\n")

##curent_timeインスタンスを使って、datetimeクラスの主なメソッドを使ってみる
print("datetimeクラスのメソッド")
print("weekday() 0->月曜~6->日曜):", type(current_datetime.weekday()), current_datetime.weekday())
print("date():", type(current_datetime.date()), current_datetime.date())
print("time():", type(current_datetime), current_datetime.time())
print("strftime():", type(current_datetime.strftime("%Y-%m-%d %H:%M:%S")), current_datetime.strftime("%Y-%m-%d %H:%M:%S"))
print("\n")

##日時を指定してdatetimeクラスのインスタンスを生成する
##year, month, dayの3引数か、hour, minute, secondの3引数のいずれかが必須
##year, month, dayの3引数のみ渡したときは、hour, minute, second, millisecond, microsecondはデフォルト値0になる
print("datetimeクラスのインスタンスの生成")
set_datetime = datetime(2000, 1, 1, hour=0, minute=0, second=0, millisecond=0, microsecond=0)
print("set_time:", set_datetime)
print("\n")

##datetimeインスタンス同士で条件式が使える
##日時が古い方が小
print("datetimeインスタンスの条件式")
print("current_time > set_time ?", current_datetime>set_datetime)
print("\n")

##datetimeインスタンスの引き算で、時間差分を取得
##時間差分は、datetime.timedeltaクラスのインスタンスとして返される
print("日時差分の計算")
td = current_datetime - set_datetime
print(set_datetime, "から", current_datetime, "までの経過時間:", td)
print("時間差分のクラス:", type(td))
print("\n")

##datetimeクラスのインスタンスに、timedeltaクラスのインスタンスを
##足したり引いたりすると時間計算ができる
print("日時の計算")
new_time1 = current_datetime + td
print(current_datetime, "から", td, "経過後の日時は", new_time1)
new_time2 = current_datetime - td
print(current_datetime, "から", td, "前の日時は", new_time2)
print("\n")

##timedeltaのインスタンスを生成すれば、datetimeに任意の日時を
##足したり引いたりできる
print("timedeltaインスタンスの生成")
##クラスを呼び出す場合はimport文で読み込む必要がある
from datetime import timedelta
##各引数のデフォルト値は全て0
mytd = timedelta(weeks=1, days=1, hours=1, minutes=1,seconds=1, milliseconds=1, microseconds=1)
print("mytd:", mytd)

実行結果

datetimeのクラスメソッドnow()
current_time: 2020-06-21 16:28:01.512707
current_timeのクラス: <class 'datetime.datetime'>

datetimeクラスのクラス属性(プロパティ)
year: 2020
month: 6
day: 21
hour: 16
minute: 28
second: 1
microsecond: 512707
timezone: None

datetimeクラスのメソッド
weekday() 0->月曜~6->日曜: <class 'int'> 6
date(): <class 'datetime.date'> 2020-06-21
time(): <class 'datetime.datetime'> 16:28:01.512707
strftime(): <class 'str'> 2020-06-21 16:28:01

datetimeクラスのインスタンスの生成
set_time: 2000-01-01 00:00:00

datetimeインスタンスの条件式
current_time > set_time ? True

日時差分の計算
2000-01-01 00:00:00 から 2020-06-21 16:28:01.512707 までの経過時間: 7477 days, 16:28:01.512707
時間差分のクラス: <class 'datetime.timedelta'>

日時の計算
2020-06-21 16:28:01.512707 から 7477 days, 16:28:01.512707 経過後の日時は 2040-12-11 08:56:03.025414
2020-06-21 16:28:01.512707 から 7477 days, 16:28:01.512707 前の日時は 2000-01-01 00:00:00

timedeltaインスタンスの生成
mytd: 8 days, 1:01:01.001001

以下、順に説明を補足します。

3.datetimeクラスのインポート

datetimeモジュールからdatetimeクラスをインポートしています。

from datetime import datetime

4.nowメソッドを使って現在日時を取得する

datetimeクラスのnowメソッドを使って、現在の日時を取得し、出力しています。

current_datetime = datetime.now()
print("current_time:", current_datetime)

nowメソッドは、インスタンスを生成することなく、クラスから直接呼び出せる、クラスメソッドです。
出力結果

current_time: 2020-06-21 16:28:01.512707

 type関数を使って、nowメソッドの戻り値のオブジェクトの型を確認しています。

print("current_timeのクラス:", type(current_datetime))

出力結果

current_timeのクラス: <class 'datetime.datetime'>

nowメソッドの戻り値は、datetimeクラスのインスタンスです。

5.datetimeクラスのインスタンス変数

nowメソッドの戻り値current_datetimeを使って、datetimeクラスのインスタンス変数を出力しています。

print("year:", current_datetime.year)
print("month:", current_datetime.month)
print("day:", current_datetime.day)
print("hour:", current_datetime.hour)
print("minute:", current_datetime.minute)
print("second:", current_datetime.second)
print("microsecond:", current_datetime.microsecond)
print("timezone:", current_datetime.tzinfo)

出力結果

year: 2020
month: 6
day: 21
hour: 16
minute: 28
second: 1
microsecond: 512707
timezone: None
timezoneがNoneとなっています。timezonがNoneの場合は、Pythonを実行しているPCやサーバ環境に合わせた時間を扱っています。timezoneに引数を設定することによって、国や地域に合わせた時間に変換したりできるようになりますが、この記事では説明を割愛します。

6.datetimeクラスのインスタンスメソッド

datetimeクラスのインスタンスメソッドを呼び出し、戻り値のオブジェクトの型と戻り値を出力しています。

print("weekday() 0->月曜~6->日曜:", type(current_datetime.weekday()), current_datetime.weekday())
print("date():", type(current_datetime.date()), current_datetime.date())
print("time():", type(current_datetime), current_datetime.time())
print("strftime():", type(current_datetime.strftime("%Y-%m-%d %H:%M:%S")), current_datetime.strftime("%Y-%m-%d %H:%M:%S"))

出力結果

weekday() 0->月曜~6->日曜: <class 'int'> 6
date(): <class 'datetime.date'> 2020-06-21
time(): <class 'datetime.datetime'> 16:28:01.512707
strftime(): <class 'str'> 2020-06-21 16:28:01

 dateメソッドは、dateteimeクラスのインスタンスを、dateクラスのインスタンスに変換したオブジェクトを返します。dateクラスは、datetimeクラスから時間以下を取り除いたクラスで、datetimeクラスと同じ、datetimeモジュールのクラスです。

 timeメソッドは、datetimeクラスの日付を取り除いた時間だけのインスタンスを返します。timeメソッドの戻り値は、datetimeクラスのインスタンスです。

 strftime(<フォーマット文字列>)メソッドは、datetimeクラスのインスタンスを、引数で指定したフォーマットの日時文字列に変換するメソッドで、よく利用します。
 フォーマット指定で使う%特殊文字の意味は以下のとおりです。

%Y:西暦4桁のdatetime.year
%m:2桁(01-12)のdatettime.month
%d:2桁(01-31)のdatetime.day
%H:2桁(00-23)のdatetime.hour
%M:2桁(00-59)のdatetime.minute
%S:2桁(00-59)のdatetime.second

 特殊文字を使ってフォーマットを自由に設定できます。
 例えば、

print(datetime.strftime("%Y年%m月%d日"))

のように、datetimeクラスのインスタンスから、日時の一部の情報だけ抜き出して使うこともできます。
この場合の出力結果は、

2020年06月21日

7.datetimeクラスのインスタンスを生成する

datetimクラスのインスタンスset_datetimeを生成しています。

set_datetime = datetime(2000, 1, 1, hour=0, minute=0, second=0, millisecond=0, microsecond=0)

8.datetimeクラスの演算

 datetimeクラスのインスタンスは、演算式を使った演算ができます。以下、紹介します。

8.1.datetimeクラスの比較演算

 datetimeクラスのインスタンスは、比較演算子を使って条件式を利用することができます。日時の古いインスタンスが小、新しいインスタンスが大となります。if文やwhile文でも使用できます。

print("current_time > set_time ?", current_datetime>set_datetime)

出力結果

current_time > set_time ? True

8.2.2つのdatetimeオブジェクトの日時差分を求める

datetimeクラスのインスタンス同士で引き算すると、2つの日時の経過時間を求めることができます。

td = current_datetime - set_datetime
print(set_datetime, "から", current_datetime, "までの経過時間:", td)
print("時間差分のクラス:", type(td))

演算結果は、timedeldaクラスのインスタンスとして返されます。
timedeltaクラスは、datetimeモジュールのクラスです。
出力結果

2000-01-01 00:00:00 から 2020-06-21 16:28:01.512707 までの経過時間: 7477 days, 16:28:01.5127072000-01-01 00:00:00 から 2020-06-21 16:28:01.512707 までの経過時間: 7477 days, 16:28:01.5127072000-01-01 00:00:00 から 2020-06-21 16:28:01.512707 までの経過時間: 7477 days, 16:28:01.512707
時間差分のクラス: <class 'datetime.timedelta'>

8.3.datetimeオブジェクトとtimedeltaオブジェクトを使った日時の計算

datetimeクラスのインスタンスに、上述のtimedeltaクラスのインスタンスを足したり引いたりすることで、日時の計算ができます。

new_time1 = current_datetime + td
print(current_datetime, "から", td, "経過後の日時は", new_time1)
new_time2 = current_datetime - td
print(current_datetime, "から", td, "前の日時は", new_time2)

実行結果

2020-06-26 10:05:12.969136 から 7482 days, 10:05:12.969136 経過後の日時は 2040-12-20 20:10:25.938272
2020-06-26 10:05:12.969136 から 7482 days, 10:05:12.969136 前の日時は 2000-01-01 00:00:00

8.4.timedeltaクラスのインスタンスを生成する

timedeltaクラスのインスタンスの生成を生成することで、任意の(経過)時間をセットできます。クラス呼び出しの際の引数を確認ください。

mytd = timedelta(weeks=1, days=1, hours=1, minutes=1,seconds=1, microseconds=1)
print("mytd:", mytd)

出力結果

mytd: 8 days, 1:01:01.000001

前の記事 次の記事


この記事が気に入ったらサポートをしてみませんか?