在Python实际开发中我们可能会需要用到指定某个年月获取第一天到最后一天的时间,下面记录一下代码段:
# -*- coding: utf-8 -*-
import time
import datetime
import random
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 00:00:00' % (year, month)
end_date = '%s-%s-%s 23:59:59' % (year, month, end)
return start_date, end_date
if __name__ == '__main__':
print(get_current_month_start_and_end('2019-05-24'))