Python日期和星期互相转换
将特定日期转换成星期
# 将日期转换成星期几
import datetime
weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
def date_to_weekday(date_str):
"""
:param date_str: 日期字符串
:return:
"""
# 将字符串转换为日期对象
date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d")
weekday_number = date_obj.weekday()
return weekdays[weekday_number]
print(date_to_weekday("2024-03-22")) # 星期五
将星期转换成最近的日期
# 将日期转换成星期几
import datetime
weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
# 将星期几转换成日期
def week_to_date(week_day):
"""
:param week_day: 星期
:return:
"""
date_obj = datetime.datetime.now()
weekday_number = date_obj.weekday()
if weekdays[weekday_number] == week_day:
return date_obj.strftime("%Y-%m-%d")
# else:
while True:
date_obj = date_obj - datetime.timedelta(days=1)
weekday_number = date_obj.weekday()
if weekdays[weekday_number] == week_day:
return date_obj.strftime("%Y-%m-%d")
print(week_to_date("星期一")) # 2024-03-18