datetime时间模块
对于天的操作:
import datetime today = str(datetime.date.today()) tmp = today.split("-") today = datetime.date(int(tmp[0]), int(tmp[1]), int(tmp[2])) print today print type(today) oneday = datetime.timedelta(days=1) print oneday yestaday = today - oneday print yestaday ############## 2017-11-07 <type 'datetime.date'> 1 day, 0:00:00 2017-11-06
对于星期的操作:
import datetime date_time = '2015-06-03' date_array = date_time.split('-') date = datetime.date(int(date_array[0]), int(date_array[1]), int(date_array[2])) week_day = date.timetuple().tm_wday # 查看今天距离星期一几天 print week_day # 计算星期一 begin_day_of_week = date - datetime.timedelta(week_day) print begin_day_of_week # 计算星期日 end_day_of_week = date + datetime.timedelta(6 - week_day) print end_day_of_week ######### 2 2015-06-01 2015-06-07
对于的月的操作:
import datetime import calendar date_time = '2015-06-03' date_array = date_time.split('-') date = datetime.date(int(date_array[0]), int(date_array[1]), int(date_array[2])) month = date.month # 月份 month_day = date.day # 当前的天数 begin_day_of_month = date - datetime.timedelta(month_day - 1) end_day_num = calendar.monthrange(int(date_array[0]), int(date_array[1]))[1] # (0,30) # (本月的第一天是星期几星期一为0,本月有多少天) end_day_of_month = date + datetime.timedelta(end_day_num - month_day)