Datetime
Datetimeの使い方 ▲
Python で日付や日時を扱うには datetimeモジュール を使用する
使い方について以下に記載する
lesson.py
import datetime
# 現在時刻を取得する
now = datetime.datetime.now()
print(now) # 2023-12-18 17:32:02.608949
print(now.isoformat()) # 2023-12-18T17:32:02.608949
print(now.strftime('%Y/%m/%d %H-%M-%S.%f')) # 2023/12/18 17-32-38.839877
# 現在の日付を取得する
today = datetime.date.today()
print(today) # 2023-12-18
print(today.isoformat()) # 2023-12-18
print(today.strftime('%Y/%m/%d')) # 2023/12/18
# 日時を作成する
t = datetime.time(hour=1, minute=10, second=5, microsecond=100)
print(t) # 01:10:05.000100
print(t.isoformat()) # 01:10:05.000100
print(t.strftime('%H-%M-%S.%f')) # 01-10-05.000100
# 日時を計算する
print(now) # 2023-12-18 17:37:18.063263
w = datetime.timedelta(weeks=1)
d = datetime.timedelta(days=2)
h = datetime.timedelta(hours=4)
s = datetime.timedelta(seconds=30)
f = datetime.timedelta(microseconds=100)
print(now - w - d - h - s - f) # 2023-12-09 13:36:48.063163
# 処理を遅延させる
import time
print('###')
time.sleep(2) # 2秒遅延させる
print('###')
# Epocタイム(1970年1月1日から数えた秒数)
print(time.time()) # 1702888769.8194346
目次