有一个统计报表需求,需要知道上个月的第一天和最后一天,来进行上个月的数据统计。
#!/usr/bin/env python3
# coding: utf-8
import calendar
def get_current_month_start_and_end(date):
"""
年份 date(2017-09-08格式)
:param date:
:return:本月第一天日期和本月最后一天日期
"""
if date.count('-') != 2:
raise ValueError('- is error')
year, month = str(date).split('-')[0], str(date).split('-')[1]
end = calendar.monthrange(int(year), int(month))[1]
start_date = '%s-%s-01' % (year, month)
end_date = '%s-%s-%s' % (year, month, end)
return start_date, end_date
print(get_current_month_start_and_end('2019-11-28'))
执行输出:
('2019-11-01', '2019-11-30')
#!/usr/bin/env python3
# coding: utf-8
import datetime
def get_yesterday():
"""
获取昨天日期
:return: 2019-11-30
"""
now_time = datetime.datetime.now()
yesterday = (now_time + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
return yesterday
print(get_yesterday())
执行输出: