def get_max_month_datetime(dt):
"""Returns the datetime representing the last microsecond of the month with
respect to the `dt` aware datetime.
"""
days_in_month = calendar.monthrange(dt.year, dt.month)[1]
tz = timezone.get_default_timezone()
new_dt = tz.normalize(
dt.replace(day=days_in_month),
)
# DST adjustments could have shifted the month or day
if new_dt.month != dt.month:
new_dt = new_dt.replace(month=dt.month)
if new_dt.day != days_in_month:
new_dt = new_dt.replace(day=days_in_month)
return new_dt.replace(hour=23, minute=59, second=59, microsecond=999999)
python类monthrange()的实例源码
def _check_day(month, day):
"""Check if day is a valid day of month.
:param month: The month to test
:param day: The day to test
:return: The day
:rtype: int
:raises TypeError: If month or day is not an int or int-like string
:raises ValueError: If month or day is out of range
"""
month = _check_month(month)
day = _check_int(day)
# Find the last day of the month
# Use a non-leap year
max_day = calendar.monthrange(2001, month)[1]
if 1 <= day <= max_day:
return day
else:
raise ValueError('day must be in %d..%d' % (1, max_day), day)
def import_census(cls, configs):
"""
Import arba census.
"""
partys = Pool().get('party.party').search([
('vat_number', '!=', None),
])
ws = cls.conect_arba()
Date = Pool().get('ir.date')
_, end_date = monthrange(Date.today().year, Date.today().month)
fecha_desde = Date.today().strftime('%Y%m') + '01'
fecha_hasta = Date.today().strftime('%Y%m') + str(end_date)
for party in partys:
data = cls.get_arba_data(ws, party, fecha_desde, fecha_hasta)
if data is not None:
if data.AlicuotaPercepcion != '':
party.AlicuotaPercepcion = Decimal(data.AlicuotaPercepcion.replace(',','.'))
if data.AlicuotaRetencion != '':
party.arba_retencion = Decimal(data.AlicuotaRetencion.replace(',','.'))
party.arba_perception = Decimal(data.AlicuotaPercepcion.replace(',','.'))
party.save()
Transaction().cursor.commit()
def main(self):
# TODO: move to Project and unit test it
cutoff = datetime.datetime.strptime(self.args.month, "%Y-%m").date()
cutoff = cutoff.replace(day=calendar.monthrange(cutoff.year, cutoff.month)[1])
e = self.make_egt(self.args.projects)
archive_results = {}
for p in e.projects:
# TODO: copy timebase and entry, ignore commands
# TODO: generate initial timebase in archived log
entries = list(l for l in p.log.entries if l.begin.date() <= cutoff)
if not entries: continue
archive_results[p.name] = self.write_archive(p, entries, cutoff)
duration = sum(e.duration for e in entries)
# TODO: use Meta.print
if "name" not in p.meta._raw:
print("Name:", p.name)
p.meta.print()
print("{}: {}".format("Total", format_duration(duration)))
print()
# TODO: use Log.print or entry.print
for l in entries:
l.print()
print()
for name, res in sorted(archive_results.items()):
print("Archived {}: {}".format(name, res))
def current_month_task_analysis():
"""
current month task analysis
"""
now = datetime.datetime.now()
no_of_days_current_month = calendar.monthrange(now.year, now.month)[1]
total_tasks = 0
total_incomplete_tasks = 0
list_of_files = list_of_tasks_files()
for some_file in range(0, len(list_of_files)):
list_of_files[some_file] = os.path.join(DIARY_CONFIG_FOLDER_PATH, list_of_files[some_file])
for some_file in list_of_files:
with open(some_file) as fp:
contents = yaml.load(fp)
for entry in contents['entries']:
total_tasks += 1
total_incomplete_tasks += (1 if entry['status'] == 0 else 0)
percent_incomplete_task = total_incomplete_tasks * 100 / total_tasks
percent_complete_task = 100 - percent_incomplete_task
entry_frequency = total_tasks * 100 / no_of_days_current_month
chalk.red('Percentage of incomplete task : ' + str(percent_incomplete_task))
chalk.green('Percentage of complete task : ' + str(percent_complete_task))
chalk.blue("Frequency of adding task (Task/Day) : " + str(entry_frequency))
def test_W_wildcard(self):
years = [2016, 2017] # leap and normal year
for year in years:
for month in range(1, 13):
_, days = calendar.monthrange(year, month)
for day in range(1, days):
weekday = calendar.weekday(year, month, day)
result = day
if weekday == 5:
result = day - 1 if day > 1 else day + 2
elif weekday == 6:
result = day + 1 if day < days else day - 2
self.assertEquals(MonthdaySetBuilder(year, month).build(str(day) + "W"), {result})
def __init__(self, year, month):
"""
Initializes monthday set builder.
:param year: Year of month to build sets for, only required for month aware 'W' and 'L' features in expressions
:param month: Month to build sets for, only required for month aware 'W' and 'L' features in expressions
"""
self.year = year
self.month = month
self._firstweekday, self._lastday = calendar.monthrange(year, month)
SetBuilder.__init__(self,
min_value=1,
max_value=self._lastday,
offset=1,
ignorecase=False,
wrap=False,
last_item_wildcard=MonthdaySetBuilder.WILDCARD_LAST_WEEKDAY)
self._post_custom_parsers = [self._parse_weekday]
def date(self, start: int = 2000, end: int = 2035,
fmt: str = '') -> str:
"""Generate a string representing of random date formatted for
the locale or as specified.
:param int start: Minimum value of year.
:param int end: Maximum value of year.
:param str fmt: Format string for date.
:return: Formatted date.
:Example:
08/16/88 (en)
"""
if not fmt:
fmt = self._data['formats'].get('date')
year = self.random.randint(start, end)
month = self.random.randint(1, 12)
d = date(year, month, self.random.randint(
1, monthrange(year, month)[1]))
return d.strftime(fmt)
def _get_next_report_date(self, cr, uid, ids, field_name, arg, context=None):
"""Return the next report date based on the last report date and report
period.
:return: a string in DEFAULT_SERVER_DATE_FORMAT representing the date"""
res = {}
for challenge in self.browse(cr, uid, ids, context=context):
last = datetime.strptime(challenge.last_report_date, DF).date()
if challenge.report_message_frequency == 'daily':
next = last + timedelta(days=1)
res[challenge.id] = next.strftime(DF)
elif challenge.report_message_frequency == 'weekly':
next = last + timedelta(days=7)
res[challenge.id] = next.strftime(DF)
elif challenge.report_message_frequency == 'monthly':
month_range = calendar.monthrange(last.year, last.month)
next = last.replace(day=month_range[1]) + timedelta(days=1)
res[challenge.id] = next.strftime(DF)
elif challenge.report_message_frequency == 'yearly':
res[challenge.id] = last.replace(year=last.year + 1).strftime(DF)
# frequency == 'once', reported when closed only
else:
res[challenge.id] = False
return res
def lowest_end(date, first_day=1):
"""Compute the ending date of the monthly period containing the given date.
More formally, given a monthly cycle starting on `first_day` day of the month,
it computes the lowest ending date that is greater than or equal to the given
`date`. Note that the ending date is inclusive, i.e. it is included in the
monthly period.
Args:
date (datetime.date): An arbitrary date.
first_day (int): The first day of the monthly cycle. It must fall
in the interval [1,28].
Returns:
datetime.date: The ending date of the monthly period containing the given date.
"""
start = greatest_start(date, first_day=first_day)
_, length = calendar.monthrange(start.year, start.month)
return start + datetime.timedelta(days=length-1)
def next(date):
"""Add one month to the given date.
Args:
date (datetime.date): The starting date.
Returns:
datetime.date: One month after the starting date unless the starting
date falls on a day that is not in the next month; in that case, it
returns the last day of the next month.
Example:
>>> import datetime
>>> next(datetime.date(2016, 1, 31))
datetime.date(2016, 2, 29)
"""
year, month = (date.year, date.month + 1) if date.month < 12 else (date.year + 1, 1)
_, length = calendar.monthrange(year, month)
day = min(length, date.day)
return datetime.date(year, month, day)
def prev(date):
"""Subtract one month from the given date.
Args:
date (datetime.date): The starting date.
Returns:
datetime.date: One month before the starting date unless the starting
date falls on a day that is not in the previous month; in that case, it
returns the last day of the previous month.
Example:
>>> import datetime
>>> prev(datetime.date(2016, 3, 31))
datetime.date(2016, 2, 29)
"""
year, month = (date.year, date.month - 1) if date.month > 1 else (date.year - 1, 12)
_, length = calendar.monthrange(year, month)
day = min(length, date.day)
return datetime.date(year, month, day)
def increment(self, when):
"""
Takes a datetime object and if it is in the past compared to the present it will
add the defined interval of time to it till it is in the future
"""
while not self.is_in_future(when):
n = now()
if self.interval == 'daily':
when = when + timedelta(days=1)
elif self.interval == 'weekly':
when = when + timedelta(days=7)
elif self.interval == 'monthly':
when = when + timedelta(days=monthrange(n.year, n.month)[1])
elif self.interval == 'yearly':
if isleap(n.year) and self.is_in_future(datetime(year=n.year, month=2, day=29)):
when = when + timedelta(days=366)
else:
when = when + timedelta(days=365)
return when
def month_add(t1, months):
"""Adds a number of months to the given date.
Note
----
The decimal part of the value corresponds to the fraction of days of the
last month that will be added.
Parameters
----------
t1 : datetime object
months : float
Returns
-------
t2 : datetime object
"""
t2 = t1 + relativedelta(months=int(months // 1))
days_in_month = calendar.monthrange(t2.year, t2.month)[1]
t2 = t2 + datetime.timedelta(seconds=days_in_month * 86400 * (months % 1))
return t2
def timevect(d_StartDate, d_EndDate, c_TimeFreq, DT=None):
f_Time = []
d_Time = []
while d_StartDate <= d_EndDate:
d_Time.append(d_StartDate)
f_Time.append(date2num(d_StartDate))
f_Date_aux = date2num(d_StartDate)
if c_TimeFreq == 'Monthly':
DT_aux = monthrange(num2date(f_Date_aux).year, num2date(f_Date_aux).month)[1]
DT = dt.timedelta(days=DT_aux)
elif c_TimeFreq == 'Yearly':
# finding out if it is a leap-year
if isleap(d_StartDate.year + 1):
DT = dt.timedelta(days=366)
else:
DT = dt.timedelta(days=365)
d_StartDate += DT
return f_Time, d_Time
def main(startyear=2014, startmonth=1, startday=1, startnewsType=0):
for year in range(2014, datetime.datetime.now().year + 1):
if year < startyear:
continue
for month in range(1, 13):
if month < startmonth:
continue
for day in range(1, calendar.monthrange(year, month)[1] + 1):
if day < startday:
continue
pool = multiprocessing.Pool()
for newsType in range(0, 7):
if newsType < startnewsType:
continue
pool.apply_async(childProcess, args=(year, month, day, newsType))
pool.close()
pool.join()
gc.collect()
## TODO:??????????????
# def restoreProcess():
## TODO:?????????
# def recoveryFromCrash():
def refresh_client(self, from_dt=None, to_dt=None):
"""
Refreshes the CalendarService endpoint, ensuring that the
event data is up-to-date. If no 'from_dt' or 'to_dt' datetimes
have been given, the range becomes this month.
"""
today = datetime.today()
first_day, last_day = monthrange(today.year, today.month)
if not from_dt:
from_dt = datetime(today.year, today.month, first_day)
if not to_dt:
to_dt = datetime(today.year, today.month, last_day)
params = dict(self.params)
params.update({
'lang': 'en-us',
'usertz': get_localzone().zone,
'startDate': from_dt.strftime('%Y-%m-%d'),
'endDate': to_dt.strftime('%Y-%m-%d')
})
req = self.session.get(self._calendar_refresh_url, params=params)
self.response = req.json()
def now_minus_delta_time(delta_time_string):
curr_datetime = datetime.datetime.now(pytz.UTC)
slop = 15 * 60 # 15 minutes of "slop" allowed in determining new backup is needed
# curr_datetime = datetime.datetime(2016, 1, 7, 10, 52, 23, tzinfo=pytz.UTC)
match = re.match('([1-9][0-9]*)([smhdwMY])', delta_time_string)
if match is None:
return None
num_units = int(match.group(1))
unit_char = match.group(2)
seconds_per_unit = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400, 'w': 604800}
if unit_char in seconds_per_unit:
delta_secs = (int(seconds_per_unit[unit_char]) * num_units) - slop
return curr_datetime - datetime.timedelta(seconds=delta_secs)
elif unit_char == 'M':
month = curr_datetime.month - 1 - num_units
year = int(curr_datetime.year + month / 12)
month = month % 12 + 1
day = min(curr_datetime.day, calendar.monthrange(year, month)[1])
return datetime.datetime(year, month, day, curr_datetime.hour, curr_datetime.minute, curr_datetime.second,
tzinfo=pytz.UTC) - datetime.timedelta(seconds=slop)
else: # unit_char == 'Y'
return datetime.datetime(curr_datetime.year + num_units, curr_datetime.month, curr_datetime.day,
curr_datetime.hour, curr_datetime.minute, curr_datetime.second, tzinfo=pytz.UTC) - \
datetime.timedelta(seconds=slop)
def get_month_period(period_range):
"""
return a start date and a end date of x complete previous month
:param period_range: number of months
:return: date_from (datetime), date_to (datetime)
"""
today = datetime.datetime.today().replace(hour=23, minute=59, second=59, microsecond=999999)
current_month = today.replace(day=1)
last_day_of_current_month = calendar.monthrange(today.year, today.month)[1]
if today.day == last_day_of_current_month:
date_from = current_month + relativedelta(months=-period_range - 1)
date_to = today
else:
date_from = current_month + relativedelta(months=-period_range)
date_to = current_month - datetime.timedelta(days=1)
return date_from, date_to
def bdays_month(month):
if month not in range(1, 13):
abort(400, 'Not a valid month')
# SO questions/36155332
_, num_days = calendar.monthrange(THIS_YEAR, month)
start = date(THIS_YEAR, month, 1)
end = date(THIS_YEAR, month, num_days)
now = _get_current_date()
# TODO: some duplication here with index()
bdays = (Birthday.query.filter(Birthday.bday <= end)
.filter(Birthday.bday >= start))
month_name = calendar.month_name[month][:3]
return render_template("index.html",
data=bdays,
now=now,
active_tab=month_name,
tabs=TABS)
def __init__(self, task, month, year, employee):
total_duration = 0
self.id = task.id
self.name = task.name
self.durations = [(0, 0) for _ in range(0, calendar.monthrange(year, month)[1])]
time_logs = TimeLog.objects.filter(workDate__year__gte=year,
workDate__month__gte=month,
workDate__year__lte=year,
workDate__month__lte=month,
task_id=task.id,
employee_id=employee)
for tl in time_logs:
index = int(tl.workDate.day)-1
self.durations[index] = (tl.duration, tl.id)
total_duration += tl.duration
self.durations.append((total_duration, 0))
def get_date(self, year):
"""
:param year: type(year): int
:return: str
"""
# year_list = [year for year in range(1996, 2018)]
# print(year_list)
for month in range(1, 13): # Jan - Dec
date_list = list(range(calendar.monthrange(year, month)[1] + 1)[1:])
if month in self.DIGIT_DICT:
month = self.DIGIT_DICT[month]
for date in date_list:
if date in self.DIGIT_DICT:
date = self.DIGIT_DICT[date]
yield "{0}-{1}-{2}".format(year, month, date)
# yield "1996-01-10" # 1
# yield "1996-02-07" # 1
# yield "2016-02-07" # 4
def get_date(self, year):
"""
:param year: type(year): int
:return: str
"""
# year_list = [year for year in range(1996, 2018)]
# print(year_list)
for month in range(1, 13): # Jan - Dec
date_list = list(range(calendar.monthrange(year, month)[1] + 1)[1:])
if month in self.DIGIT_DICT:
month = self.DIGIT_DICT[month]
for date in date_list:
if date in self.DIGIT_DICT:
date = self.DIGIT_DICT[date]
yield "{0}-{1}-{2}".format(year, month, date)
# yield "1996-01-10" # 1
# yield "1996-02-07" # 1
# yield "2016-02-07" # 4
def get_next_value(self, date, field):
# Figure out the weekday of the month's first day and the number of days in that month
first_day_wday, last_day = monthrange(date.year, date.month)
# Calculate which day of the month is the first of the target weekdays
first_hit_day = self.weekday - first_day_wday + 1
if first_hit_day <= 0:
first_hit_day += 7
# Calculate what day of the month the target weekday would be
if self.option_num < 5:
target_day = first_hit_day + self.option_num * 7
else:
target_day = first_hit_day + ((last_day - first_hit_day) / 7) * 7
if target_day <= last_day and target_day >= date.day:
return target_day
def get_next_value(self, date, field):
# Figure out the weekday of the month's first day and the number of days in that month
first_day_wday, last_day = monthrange(date.year, date.month)
# Calculate which day of the month is the first of the target weekdays
first_hit_day = self.weekday - first_day_wday + 1
if first_hit_day <= 0:
first_hit_day += 7
# Calculate what day of the month the target weekday would be
if self.option_num < 5:
target_day = first_hit_day + self.option_num * 7
else:
target_day = first_hit_day + ((last_day - first_hit_day) / 7) * 7
if target_day <= last_day and target_day >= date.day:
return target_day
def test_total_file_count_for_this_month(self):
"""
tests that the current amount of new files uploaded for the current month is correct
"""
images = ['red.gif', 'blue.gif', 'green.gif', 'love.gif']
for image in images:
file_name = image
file_content_type = 'image/gif'
file_path = os.path.abspath("test/files/%s" % (file_name))
file_sha1 = Sourcefile.get_sha1_file_key(file_path)
sf = Sharedfile.create_from_file(
file_path = file_path,
file_name = file_name,
sha1_value = file_sha1,
content_type = file_content_type,
user_id = self.user.id)
month_days = calendar.monthrange(datetime.utcnow().year,datetime.utcnow().month)
start_time = datetime.utcnow().strftime("%Y-%m-01")
end_time = datetime.utcnow().strftime("%Y-%m-" + str(month_days[1]) )
self.assertEqual(self.user.uploaded_kilobytes(start_time=start_time, end_time=end_time), 72)
def get_allocation_price(self, resource, name=None, today=None):
quota = self.get_quota(resource, name)
if quota == -1:
return 0
if today is None:
today = date.today()
rate = self.get_rate(resource, name)
#month_range = calendar.monthrange(today.year, today.month)[1]
# for variable month days/hours
#price = decimal.Decimal('0.24') * rate * decimal.Decimal(quota) * decimal.Decimal(month_range)
# for fixed month days/hours: 730
price = D('73.0') * rate * decimal.Decimal(quota)
return price
def run(self, query, args):
self.start = args.get(constants.PARAM_START_DATE)
self.end = args.get(constants.PARAM_END_DATE)
self.validate_start_end_dates()
if self.errors:
return
start_date, end_date = None, None
if self.start:
start_date = str(iso8601.parse_date(self.start).date())
if self.end:
end_date = iso8601.parse_date(self.end).date()
if '-' not in self.end: # Solo especifica año
end_date = datetime.date(end_date.year, 12, 31)
if self.end.count('-') == 1: # Especifica año y mes
# Obtengo el último día del mes, monthrange devuelve
# tupla (month, last_day)
days = monthrange(end_date.year, end_date.month)[1]
end_date = datetime.date(end_date.year, end_date.month, days)
query.add_filter(start_date, end_date)
def get_interval(sometime, interval):
"""Gets the interval for some time
:param sometime: A datetime.datetime object
:param interval: A string to indicate interval
:returns: The start and endtime for the interval
:rtype: datetime.datetime, datetime.datetime
"""
year = sometime.year
month = sometime.month
if interval == ReportSubscription.MONTH:
_day, days = calendar.monthrange(year, month)
start = datetime(year, month, 1)
end = datetime(year, month, days) + timedelta(days=1)
elif interval == ReportSubscription.WEEK:
start = sometime - timedelta(days=sometime.weekday())
end = start + timedelta(days=7)
else:
# interval is one day
start = sometime
end = start + timedelta(days=1)
return start, end
def calendar(request, year=None, month=None):
customer = None
if request.GET.has_key('customer_id'):
customer = Customer.objects.get(pk=request.GET['customer_id'])
if year is None or month is None:
start_date = dt.datetime.strptime('%s.%s' %(dt.datetime.now().month, dt.datetime.now().year), '%m.%Y')
else:
start_date = dt.datetime.strptime('%s.%s' %(month, year), '%m.%Y')
offset = start_date.weekday()+cl.monthrange(start_date.year, start_date.month)[1]
if offset == 28:
weeks = [0,1,2,3]
elif offset > 28 and offset < 36:
weeks = [0,1,2,3,4]
else:
weeks = [0,1,2,3,4,5]
return render(request, 'calendar.html', { 'offset':offset, 'customer':customer, 'prev':(start_date+dt.timedelta(days=-1)), 'next':(start_date+dt.timedelta(days=32)),
'cal_date':start_date, 'start_date':start_date.strftime('%m.%Y'), 'weeks':weeks, 'days':[0,1,2,3,4,5,6] })