Datetime
String to Datetime
from datetime import datetime
date_str = '09-19-2022'
date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
print(type(date_object))
print(date_object) # printed in default format
# Output:
# <class 'datetime.date'>
# 2022-09-19
from datetime import datetime
time_str = '13::55::26'
time_object = datetime.strptime(time_str, '%H::%M::%S').time()
print(type(time_object))
print(time_object)
# Output:
# <class 'datetime.time'>
# 13:55:26
from datetime import datetime
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')
date_str_de_DE = '16-Dezember-2022 Freitag' # de_DE locale
datetime_object = datetime.strptime(date_str_de_DE, '%d-%B-%Y %A')
print(type(datetime_object))
print(datetime_object)
# Output:
# <class 'datetime.datetime'>
# 2022-12-16 00:00:00
timedelta
日期/時間計算
import datetime
today = datetime.datetime.now()
yesterday = today - datetime.timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1)
nextweek = today + datetime.timedelta(weeks=1)
print(today) # 2021-10-19 07:01:22.669886
print(yesterday) # 2021-10-18 07:01:22.669886
print(tomorrow) # 2021-10-20 07:01:22.669886
print(nextweek) # 2021-10-26 07:01:22.669886