业务场景:python
咱们常常会跑一些月级别或者周级别的报表。算法
周级别的报表还比较好肯定,就是七天前的直接用timedelta(days=7)来获取开始日期就能够了;函数
可是月级别的报表就要麻烦一些,由于timedelta这个函数没有month这个参数,那咱们怎么来获取一个月前的一号呢,还要考虑到这个月有多少天,会不会跨年,之类的...学习
我今天想到了一个简单的办法,分享给你们spa
有了这个办法,就不用再去判断闰年那些很麻烦的逻辑了code
若是你们发现这个算法有什么问题能够指出来,共同窗习blog
1 from datetime import date 2 from datetime import timedelta 3 4 def get_last_month_first_day(date): 5 date_terminal = 26 + date.day 6 res_date = date - timedelta(days=date_terminal) 7 while 1: 8 if res_date.day == 1: 9 break 10 else: 11 res_date -= timedelta(days=1) 12 return res_date 13 14 15 if __name__ == '__main__': 16 test_date_a = date(2016, 9,3) 17 test_date_b = date(2016, 10, 1) 18 test_date_c = date(2016, 2, 28) 19 test_date_d = date(2016, 1, 1) 20 print map(get_last_month_first_day, [ 21 test_date_a, test_date_b, test_date_c, test_date_d])
----------------2017-07-16-------------------------terminal
如今再看这道题,我又有了新的办法,对比以前的写法不知道好了多少get
def get_last_month_first_day_v2(d): return datetime.date(d.year - (d.month==1), d.month - 1 or 12, 1)