0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonの日付date

Last updated at Posted at 2021-07-08

dateオブジェクトの作成

datatimeモジュールのdateオブジェクトを作成します。

from datetime import date

d = date(2021, 7, 8)

dateクラス属性

d = date(2021, 7, 8)
print(d.year)
print(d.month)
print(d.day)

出力:

2021
7
8

日付の曜日を知る

d = date(2021, 7, 8)
print(d.weekday())

出力:

3
  • 0=月曜日
  • 1=火曜日
  • ...
  • 6=日曜日

日付の計算

日付の最大/最小値

d1 = date(2021, 3, 9)
d2 = date(2021, 7, 8)

print(min([d1, d2]))
print(max([d1, d2]))

出力:

2021-03-09
2021-07-08

日付の引き算

d1 = date(2021, 3, 9)
d2 = date(2021, 7, 8)

print((d1 - d2).days)
print((d2 - d1).days)

出力:

-121
121

日付の足し算

datetimeモジュールのtimedeltaクラスは、date/time/datetimeクラスの二つのインスタンス間の時間差をマイクロ秒精度で表す経過時間値です。

from datetime import timedelta

d1 = date(2021, 3, 9)
td = timedelta(days=121)

print(d1 + td)

出力:

2021-07-08

dateを文字列に変換する

dateをISO 8601フォーマットの文字列に変換する場合、isoformatメソッドを使用します。
dateを自由なフォーマットに変換する場合、strftimeメソッドを使用します。

from datetime import date
d = date(2021, 7, 8)

print(d.isoformat())
print(d.strftime('Date is %Y/%m/%d'))

出力:

2021-07-08
Date is 2021/07/08

参考情報

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?