由于工作中经常用到关于用户自定义时间,来进行后台数据的查询,特意整理了一下工作中常用的到的关于时间列表的一个函数,可以计算出某一年中的具体哪个周的开始和结束日期,某个周的具体日期列表(2015年38周),自定义时间段的具体日期列表(20150901-20151010)
1、计算当前日期:
import datetime print datetime.datetime.now()
2、计算昨天和明天的日期
yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y%m%d") tomorrow = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y%m%d")
3、计算某一月有多少天
import calendar monthRange = calendar.monthrange(2013,6) print monthRange 输出: (5, 30) 输出的是一个元组,第一个元素是上一个月的最后一天为星期几(0-6),星期天为0;第二个元素是这个月的天数。
4、计算周的日期函数。包含某一周开始、结束日期,周的详细日期列表
import datetime def allweeks(week): "计算一年内所有周的具体日期" _week = int(week)-1 current = datetime.datetime.now() start = datetime.date(current.year,1,1) last_day = datetime.date(current.year,12,31) isfirst = start.weekday() last_week = last_day.strftime('%W') weeks={} #计算出一年中每个周的开始和结束日期。例如:0: [datetime.date(2015, 1, 1), datetime.date(2015, 1, 4)] date_list_for_week = [] #用于得出具体的某一个周的具体天数列表:例如: 第9周:['20150223', '20150224', '20150225', '20150226', '20150227', '20150228', '20150301'] if isfirst !=0: end = datetime.timedelta(7-start.weekday()-1) weeks[0]=[start,start+end] start += datetime.timedelta(7 - start.weekday()) for i in range(0,int(last_week)): days = datetime.timedelta(weeks=i) end = start + days if i+1 == int(last_week): weeks[i+1] = [end,last_day] else: weeks[i+1] = [end,end + datetime.timedelta(6)] starttime = ''.join(str(weeks[_week][0]).split('-'))#计算出给出周的开始日期,如20150907 endtime = ''.join(str(weeks[_week][1]).split("-"))#计算出给出周的结束日期,如201509013 delta = datetime.timedelta(days=1) startdate = datetime.datetime(int(starttime[0:4]),int(starttime[4:6]),int(starttime[6:8])) if int(starttime[4:6]) == int(endtime[4:6]): for i in range(int(endtime[6:]) - int(starttime[6:])+1): days = (startdate +delta*i).strftime('%Y%m%d') date_list_for_week.append(days) elif int(starttime[4:6]) != int(endtime[4:6]): for i in range(7): days = (startdate +delta*i).strftime('%Y%m%d') date_list_for_week.append(days) return date_list_for_week,weeks,starttime,endtime if __name__ == "__main__": week =9 print allweeks(week)
5、计算自定义时间的日期函数。(比如计算20150811-20150922之间的日期列表)
import datetime def get_datelist(starttime,endtime): startdate = datetime.datetime(int(starttime[0:4]),int(starttime[4:6]),int(starttime[6:8])) #now = datetime.datetime.now() delta = datetime.timedelta(days=1) # my_yestoday = startdate + delta # my_yes_time = my_yestoday.strftime('%Y%m%d') n = 0 date_list = [] while 1: if starttime<=endtime: days = (startdate + delta*n).strftime('%Y%m%d') n = n+1 date_list.append(days) if days == endtime: break return date_list print get_yestoday('20150811','20150922')
6、将自定义时间分割成星期来进行取值,不足一星期的按天来取值
def startdate_enddate_weeks_list(startdate,enddate): '''计算startdate---enddate的周所属的周和周包含的日期列表 week_date_start_end {1: ['20181231','20190106'],...} ''' start_date=datetime.datetime.strptime(str(startdate),'%Y%m%d') end_date=datetime.datetime.strptime(str(enddate),'%Y%m%d') _u=datetime.timedelta(days=1) n=0 week_date=collections.OrderedDict() date=[] while 1: _time=start_date+n*_u y,w=_time.isocalendar()[:2] year_week=str(y)+str(w) if week_date.has_key(year_week): date.append(_time.strftime('%Y%m%d')) else: date=[_time.strftime('%Y%m%d')] week_date[year_week]=date n=n+1 if _time==end_date: break return week_date a=startdate_enddate_weeks_list("20151011","20151102") print a ([('201541', ['20151011']), ('201542', ['20151012', '20151013', '20151014', '20151015', '20151016', '20151017', '20151018']), ('201543', ['20151019', '20151020', '20151021', '20151022', '20151023', '20151024', '20151025']), ('201544', ['20151026', '20151027', '20151028', '20151029', '20151030', '20151031', '20151101']), ('201545', ['20151102'])])
7、计算当前天的前一周的天数。
def seven_day_list(year_mon_day,i,n): '''计算当前天的前七天列表,例如:2015-09-10---------2015-10-10''' myday = datetime.datetime( int(year_mon_day[0:4]),int(year_mon_day[4:6]),int(year_mon_day[6:8]) ) day_list = [] for i in xrange(i,n): days = (myday + datetime.timedelta(days=-i)).strftime('%Y-%m-%d') day_list.append(days) return day_list[::-1]