Python - 日付と時刻: datetime
日付と時刻: datetime
Python では、datetime
モジュールの datetime
オブジェクトを使って日付や時刻の取得を行えます。以下は、datetime
オブジェクトを使った現在時刻を取得するサンプルコードです。
import datetime
d = datetime.datetime
# 現在時刻
print(d.today()) # 2021-01-04 17:43:29.050678
# 現在時刻
print(d.now()) # 2021-01-04 17:43:29.051616
datetime
を使った現在時刻の取得datetime
オブジェクトからは、年・月・日・時・分・秒、そしてマイクロ秒の情報を取得できます。
import datetime
d = datetime.datetime.now()
print(d) # 2021-01-04 17:51:07.416799
# 年
print(d.year) # 2021
# 月
print(d.month) # 1
# 日
print(d.day) # 4
# 時
print(d.hour) # 17
# 分
print(d.minute) # 51
# 秒
print(d.second) # 7
# マイクロ秒
print(d.microsecond) # 416799
# 0 埋めする場合
print("{0:04d}".format(d.year)) # 2021
print("{0:02d}".format(d.month)) # 01
print("{0:02d}".format(d.day)) # 04
print("{0:02d}".format(d.hour)) # 17
print("{0:02d}".format(d.minute)) # 51
print("{0:02d}".format(d.second)) # 07
print("{0:06d}".format(d.microsecond)) # 416799
年・月・日・時・分・秒・マイクロ秒の取得
任意の日付・時刻を取得したい場合は、datetime
にパラメータを与えることで生成・取得可能です。ただし、年・月・日のパラメータは必須で、その他の時・分・秒・マイクロ秒は省略できます。省略した場合は 0 になります。
import datetime
d = datetime.datetime(2000, 1, 2, 3, 4, 5, 6)
print(d) # 2000-01-02 03:04:05.000006
# 年
print(d.year) # 2000
# 月
print(d.month) # 1
# 日
print(d.day) # 2
# 時
print(d.hour) # 3
# 分
print(d.minute) # 4
# 秒
print(d.second) # 5
# マイクロ秒
print(d.microsecond) # 6
任意の年・月・日・時・分・秒・マイクロ秒の生成・取得