1、获取指定日期所在的周的每一天
/Users/nisj/PycharmProjects/EsDataProc/bi-static/calc_day_in_week.py
# -*- coding=utf-8 -*-
import datetime
def week_get(vdate):
dayscount = datetime.timedelta(days=vdate.isoweekday())
dayfrom = vdate - dayscount + datetime.timedelta(days=1)
dayto = vdate - dayscount + datetime.timedelta(days=7)
print ' ~~ '.join([str(dayfrom), str(dayto)])
week7 = []
i = 0
while (i <= 6):
week7.append('周'+str(i+1)+': '+str(dayfrom + datetime.timedelta(days=i)))
i += 1
return week7
if __name__ == '__main__':
vdate_str = '2017-01-09'
vdate = datetime.datetime.strptime(vdate_str, '%Y-%m-%d').date()
for week in week_get(vdate):
print week
2、获取指定日期所在的周及周的每一天
/Users/nisj/PycharmProjects/EsDataProc/bi-static/calc_day_in_weekYear.py
# -*- coding=utf-8 -*-
import datetime
def week_get(vdate):
dayscount = datetime.timedelta(days=vdate.isoweekday())
dayfrom = vdate - dayscount + datetime.timedelta(days=1)
dayto = vdate - dayscount + datetime.timedelta(days=7)
print ' ~~ '.join([str(dayfrom), str(dayto)])
week7 = []
i = 0
while (i <= 6):
week7.append('周'+str(i+1)+': '+str(dayfrom + datetime.timedelta(days=i)))
i += 1
return week7
def weekInYear(vdate_str):
date = vdate_str
yearWeek = datetime.date(int(date[0:4]), int(date[5:7]), int(date[8:10])).isocalendar()[0:2]
return str(yearWeek[0])+'#'+str(yearWeek[1])
if __name__ == '__main__':
vdate_str = '2017-01-20'
vdate = datetime.datetime.strptime(vdate_str, '%Y-%m-%d').date()
for week in week_get(vdate):
for weekYear in (weekInYear(vdate_str).split()):
print weekYear,week
3、获取当前时间的前一天,前一周,前一个月
/Users/nisj/PycharmProjects/EsDataProc/bi-static/calc_dayInDayWeekMonth.py
import datetime
def day_get(d):
oneday = datetime.timedelta(days=1)
day = d - oneday
date_from = datetime.datetime(day.year, day.month, day.day, 0, 0, 0)
date_to = datetime.datetime(day.year, day.month, day.day, 23, 59, 59)
print '---'.join([str(date_from), str(date_to)])
def week_get(d):
dayscount = datetime.timedelta(days=d.isoweekday())
dayto = d - dayscount
sixdays = datetime.timedelta(days=6)
dayfrom = dayto - sixdays
date_from = datetime.datetime(dayfrom.year, dayfrom.month, dayfrom.day, 0, 0, 0)
date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
print '---'.join([str(date_from), str(date_to)])
def month_get(d):
dayscount = datetime.timedelta(days=d.day)
dayto = d - dayscount
date_from = datetime.datetime(dayto.year, dayto.month, 1, 0, 0, 0)
date_to = datetime.datetime(dayto.year, dayto.month, dayto.day, 23, 59, 59)
print '---'.join([str(date_from), str(date_to)])
if __name__ == '__main__':
d = datetime.datetime.now()
day_get(d)
week_get(d)
month_get(d)