strptimeとstrftimeの違い
strptime
文字列(string)を日付(datetime)に変換する。
# string型の日付 str_date = '2020-06-06' # datetime型に変換 date = datetime.strptime(str_date, "%Y-%m-%d") print(date) #出力:2020-06-06 00:00:00
strftime
日付(datetime)を文字列(string)に変換する。
# datetime型の日付 date = datetime(2020,06,06) # 2020-06-06 # string型に変換 str_date = date.strftime("%Y-%m-%d") print(str_date) #出力:2020-06-06
Python3.6以降ではf-stringsを使って文字列に変換することもできます。
# datetime型の日付 date = datetime(2020,06,06) # 2020-06-06 # f-stringsでstring型に変換 str_date = f'{date:%Y-%m-%d}' print(str_date) #出力:2020-06-06