def add_months(sourcedate,months):
month = sourcedate.month - 1 + months
year = int(sourcedate.year + month / 12 )
month = month % 12 + 1
day = min(sourcedate.day,calendar.monthrange(year,month)[1])
return datetime.date(year,month,day)
python类monthrange()的实例源码
def __init__(self, month, year, indent_level, indent_style):
'x.__init__(...) initializes x'
calendar.setfirstweekday(calendar.SUNDAY)
matrix = calendar.monthcalendar(year, month)
self.__table = HTML_Table(len(matrix) + 1, 7, indent_level, indent_style)
for column, text in enumerate(calendar.day_name[-1:] + calendar.day_name[:-1]):
self.__table.mutate(0, column, '<b>%s</b>' % text)
for row, week in enumerate(matrix):
for column, day in enumerate(week):
if day:
self.__table.mutate(row + 1, column, '<b>%02d</b>\n<hr>\n' % day)
self.__weekday, self.__alldays = calendar.monthrange(year, month)
self.__weekday = ((self.__weekday + 1) % 7) + 6
def next_month(self):
"""Update calendar to show the next month."""
if self._selection_is_visible: self._clear_selection()
date = self.datetime(self._year, self._month, 1) + \
self.timedelta(days=calendar.monthrange(self._year, self._month)[1] + 1)
self._build_calendar(date.year, date.month) # reconstuct calendar
def _get_yesterdays_date():
current = date.today()
current_time = datetime.utcnow()
if current.day == 1:
if current_time.hour <= 5:
return date(current.year, current.month-1, (calendar.monthrange(current.year, current.month-1)[2])).strftime('%Y-%m-%d')
else:
return date(current.year, current.month-1, (calendar.monthrange(current.year, current.month-1)[1])).strftime('%Y-%m-%d')
else:
if current_time.hour <= 5:
return date(current.year, current.month, current.day-2).strftime('%Y-%m-%d')
else:
return date(current.year, current.month, current.day-1).strftime('%Y-%m-%d')
def _get_last_month():
current = date.today()
if current.day == 31:
return date(current.year, current.month-1, (calendar.monthrange(current.year, current.month-1)[1])).strftime('%Y-%m')
else:
return date(current.year, current.month-1, current.day).strftime('%Y-%m')
def get_record(omni_path,
d1,
d2,
template='omni_min{year:04d}{month:02d}.asc',
inclusive=True):
"""
Gather an OMNI data record spanning *d1* to *d2* and return a
:class:`PD.DataFrame`. Use file OMNI data record file names
specified by *template*. If *inclusive*, the range is *d1* to *d2*
with equality on both bounds.
"""
df_list = []
for year in range(d1.year, d2.year + 1):
for month in range(1, 13):
date1 = datetime(year, month, 1)
date2 = date1 + timedelta(days=monthrange(year, month)[1])
if not (date1 <= d1 <= date2 or date1 <= d2 <= date2):
continue
omni_fname = os.path.join(omni_path,
template.format(year=year,
month=month))
if not os.path.isfile(omni_fname):
logger.warning('could not find {} --- skipping'.format(omni_fname))
continue
logger.info('parsing {}'.format(omni_fname))
df_list.append(parse(omni_fname))
df = PD.concat(df_list)
if inclusive:
return df[d1:d2]
else:
return df[d1:d2].iloc[:-1]
def nearest_dom(year, month, day):
"""
Return day adjusted as necessary to fit within the days available in
year/month. For example:
nearest_dom(2017, 2, 30) #=> 28
"""
return min(calendar.monthrange(year, month)[1], day)
def t(self):
"Number of days in the given month; i.e. '28' to '31'"
return '%02d' % calendar.monthrange(self.data.year, self.data.month)[1]
def __init__(self, year=None, month=None, day=None, hour=None, minute=None,
second=None, microsecond=None):
if isinstance(year, datetime):
dt = year
self.year, self.month, self.day = dt.year, dt.month, dt.day
self.hour, self.minute, self.second = dt.hour, dt.minute, dt.second
self.microsecond = dt.microsecond
else:
if month is not None and (month < 1 or month > 12):
raise TimeError("month must be in 1..12")
if day is not None and day < 1:
raise TimeError("day must be greater than 1")
if (year is not None and month is not None and day is not None
and day > calendar.monthrange(year, month)[1]):
raise TimeError("day is out of range for month")
if hour is not None and (hour < 0 or hour > 23):
raise TimeError("hour must be in 0..23")
if minute is not None and (minute < 0 or minute > 59):
raise TimeError("minute must be in 0..59")
if second is not None and (second < 0 or second > 59):
raise TimeError("second must be in 0..59")
if microsecond is not None and (microsecond < 0
or microsecond > 999999):
raise TimeError("microsecond must be in 0..999999")
self.year, self.month, self.day = year, month, day
self.hour, self.minute, self.second = hour, minute, second
self.microsecond = microsecond
def ceil(self):
"""Returns a ``datetime`` version of this object with all unspecified
(None) attributes replaced by their highest values.
This method raises an error if the ``adatetime`` object has no year.
>>> adt = adatetime(year=2009, month=5)
>>> adt.floor()
datetime.datetime(2009, 5, 30, 23, 59, 59, 999999)
"""
y, m, d, h, mn, s, ms = (self.year, self.month, self.day, self.hour,
self.minute, self.second, self.microsecond)
if y is None:
raise ValueError("Date has no year")
if m is None:
m = 12
if d is None:
d = calendar.monthrange(y, m)[1]
if h is None:
h = 23
if mn is None:
mn = 59
if s is None:
s = 59
if ms is None:
ms = 999999
return datetime(y, m, d, h, mn, s, ms)
def getMonth(date):
first_day = date.replace(day = 1)
last_day = date.replace(day = calendar.monthrange(date.year, date.month)[1])
return first_day, last_day
def wd_manage_apply(request, month, year, contract):
c = Contract.objects.get(id=int(contract), user=request.user)
month = int(month)
year = int(year)
firstDayOfMonth = datetime(year, month, 1, 0, 0, 1, 0).weekday()
daysInMonth = monthrange(year, month)
workL = WorkLog.objects.get(contract=c, month=month, year=year)
# First try apply all anual activities
anuals = c.fixedworkdustactivity_set.all()
for a in anuals:
if a.week_day > firstDayOfMonth:
anualStep = 1 + a.week_day - firstDayOfMonth
elif a.week_day == firstDayOfMonth:
anualStep = 1
else:
anualStep = 1 + 7 - firstDayOfMonth + a.week_day
while anualStep <= daysInMonth[1] and workL.calcHours() + a.avg_length <= c.hours:
wt = WorkTime()
wt.work_log = workL
if a.avg_length >= 6:
wt.pause = 1
else:
wt.pause = 0
wt.begin = datetime(year, month, anualStep, a.start.hour, a.start.minute, 0, 0)
beginstamp = (wt.begin - datetime(1970, 1, 1)).total_seconds()
wt.end = datetime.fromtimestamp(beginstamp +
a.avg_length * 60.0*60.0 + wt.pause * 60.0*60.0)
# wt.end = wt.begin.replace(hour=int(wt.begin.hour + math.floor(a.avg_length) + wt.pause))
# wt.end = wt.end.replace(minute=int(round((a.avg_length - math.floor(a.avg_length)) * 60)))
wt.activity = a.description
wt.clean_fields(year, month)
wt.save()
anualStep += 7
# Then fill with "other" activities
filler = FillerWorkDustActivity.objects.all()
largestFreeSlot = 0
smallestFiller = filler.aggregate(Min('avg_length'))['avg_length__min']
while not smallestFiller == None and largestFreeSlot >= smallestFiller:
pass
return redirect("/?month=" + str(month) + "&year=" + str(year) + "#" + str(c.id))
def days_in_month(self):
"""
????????
:return:
"""
return calendar.monthrange(self.year, self.month)[1]
def get_holiday_df(year,month):
monthRange = calendar.monthrange(year,month)[-1]
mask_month = "%s%s"%(year,month)
if month < 10:
mask_month = "%s0%s"%(year,month)
mask = get_holiday_mask(mask_month)
a = pd.DataFrame(index = pd.date_range('%s-%s-1'%(year,month), periods=monthRange, freq='D'))
index = pd.Series(a.index)
mask_df = index.apply(lambda x:mask[x.day] if x.day in mask else 0)
mask_df.index = index
a['holiday'] = (mask_df == 1).astype('int')
a['festday'] = (mask_df == 2).astype('int')
return a
def get_month_range(start_date=None, next_month=False):
if start_date is None:
start_date = datetime.date.today()
month = start_date.month
year = start_date.year
if next_month:
month = 1 if start_date.month == 12 else start_date.month + 1
if month == 1:
year += 1
start_date = start_date.replace(day=1, month=month, year=year)
_, days_in_month = calendar.monthrange(year, month)
end_date = start_date + datetime.timedelta(days=days_in_month-1)
return (start_date, end_date)
def is_end_of_month(self):
""" returns true, if the current day is the end of month """
return monthrange(self.year, self.month)[1] == self.day
def add_month(self, months):
""" introduces calculation with months """
new_year = self.year + int((self.month + months - 1)/12)
new_month = ((self.month + months - 1) % 12) + 1
new_day = min(self.day, monthrange(new_year, new_month)[1])
return Bank_Date(year = new_year, month = new_month, day = new_day)
def get_days_per_year(year):
# returns the number of days per year
return 365 if monthrange(year, 2)[1] == 28 else 366
# deprecated, old methods for maniuplating datetime
def add_month(start_date, months):
""" introduces calculation with months """
new_year = start_date.year + int((start_date.month + months - 1)/12)
new_month = ((start_date.month + months - 1) % 12) + 1
new_day = min(start_date.day, monthrange(new_year, new_month)[1])
new_date = date(new_year, new_month, new_day)
return new_date
def list_days_of_month(year, month):
lastday = calendar.monthrange(year, month)[1]
days = [format_date(year, month, day) for day in range(1, lastday + 1)]
return days