どうも、ちょげ(@chogetarou)です。
DateTimeから時刻のみを文字列として取得する方法を紹介します。
方法

DateTimeから時刻のみを文字列として取得するには、strftime()を使います。
まず、datetimeからstrftime()を呼び出します。
そして、stftime()の引数に「”%H:%M:%S”」を指定します。
time_str = date.strftime("%H:%M:%S")
上記のstrftime()は、DateTimeの時刻のみを文字列として返します。
使用例
from datetime import datetime
date = datetime.now()
time_str = date.strftime("%H:%M:%S")
print(date) #2022-06-28 08:00:08.664978
print(time_str) #08:00:08
print(type(time_str)) #<class 'str'>
コメント