datetime的应用
一.根据当前日期得到当前月末日期
import datetime as dt
year = dt.datetime.today().year
mouth = dt.datetime.today().month
start = dt.datetime(year, mouth, 1).date() # 月初
month_end = dt.datetime(year, mouth, calendar.monthrange(year, mouth)[1]).date() #月末
二.根据当前日期得到星期N的日期
#获取周五日期
def friday(self):
dt_obj = dt.datetime.now() #得到当前时间
week_day = "friday" #填你想得到周几的日期
d = dict(zip(("monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"),
range(7))) # datetime 模块中,星期一到星期天对应数字 0 到 6
delta_hour = dt.timedelta(days=1) # 改变幅度为 1 天
while dt_obj.weekday() != d.get(week_day):
if dt_obj.weekday() > d.get(week_day):
dt_obj -= delta_hour
elif dt_obj.weekday() < d.get(week_day):
dt_obj += delta_hour
else:
pass
return dt_obj.strftime("%Y-%m-%d") #字符串格式