Pythonでは、時間を文字列に変換するために strftime()
関数を使用します。この関数は、日付、時間、または日時オブジェクトを使用して日付と時間を表現する文字列を返します。
以下に、現在の日付と時間を含む日時オブジェクトを異なる文字列形式に変換するプログラムの例を示します。
from datetime import datetime
now = datetime.now() # 現在の日付と時間
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:", date_time)
このプログラムを実行すると、以下のような出力が得られます。
year: 2018
month: 12
day: 24
time: 04:59:31
date and time: 12/24/2018, 04:59:31
ここで、year
、day
、time
、date_time
は文字列であり、now
は日時オブジェクトです。
strftime()
関数は、1つ以上の形式コードを引数として取り、それに基づいてフォーマットされた文字列を返します。strftime()
関数に渡す文字列には、複数の形式コードを含めることができます。
また、タイムスタンプから文字列を作成する例もあります。
from datetime import datetime
timestamp = 1528797322
date_time = datetime.fromtimestamp(timestamp)
print("Date time object:", date_time)
d = date_time.strftime("%m/%d/%Y, %H:%M:%S")
print("Output 2:", d)
d = date_time.strftime("%d %b, %Y")
print("Output 3:", d)
d = date_time.strftime("%d %B, %Y")
print("Output 4:", d)
d = date_time.strftime("%I%p")
print("Output 5:", d)
このプログラムを実行すると、以下のような出力が得られます。
Date time object: 2018-06-12 09:55:22
Output 2: 06/12/2018, 09:55:22
Output 3: 12 Jun, 2018
Output 4: 12 June, 2018
Output 5: 09AM
以上がPythonで時間を文字列に変換する方法についての基本的な説明です。これらの知識を活用して、Pythonプログラミングの幅を広げてみてください。