Python-时间及日期-07-获取本周或上周几具体日期
系统 :Windows 7 语言版本 :Anaconda3-4.3.0.1-Windows-x86_64 编辑器 :pycharm-community-2016.3.2 Python :3.6.0
- 这个系列讲讲 Python 对时间及日期的操作
- 今天讲讲获取本周几的日期或者上周周几的日期
- 涉及模块: datetime
Part 1:实现功能1
- 获取本周几的日期,例如获取本周周四的日期
Part 2:代码1
import datetime
def get_current_weekday(n):
today_info = datetime.date.today()
print("今天是:", today_info)
today_n = today_info.weekday()
day_n = today_info
one_day = datetime.timedelta(days=1)
if today_n < n:
while day_n.weekday() != n:
day_n += one_day
else:
while day_n.weekday() != n:
day_n -= one_day
return day_n
current_week_day = get_current_weekday(3)
print("本周周四是:", current_week_day)
代码截图
运行结果
实际情况
Part 3:实现功能2
- 获取上周几的日期,例如获取上周3的日期
Part 4:代码2
import datetime
def get_last_wek_weekday(n):
today_info = datetime.date.today()
print("今天是:", today_info)
one_day = datetime.timedelta(days=1)
seven_day = datetime.timedelta(days=7)
last_week_day = today_info - seven_day
last_week_day_n = last_week_day.weekday()
print("上周的今天是:", last_week_day)
if last_week_day_n < n:
while last_week_day.weekday() != n:
last_week_day += one_day
else:
while last_week_day.weekday() != n:
last_week_day -= one_day
return last_week_day
last_week_day_2 = get_last_wek_weekday(2)
print("上周周三是:", last_week_day_2)
代码截图
运行结果
实际情况