本文就总结一下在Python开发中常用的日期处理,比如月初、月末、第几周、当周的第几天、当月的第几天等一系列的处理办法,因目前python写的代码不多,基本上都是一些小工具之类的,故此文会持续更新。
1.获取当月的第一天(月初)
""" 判断输入的日期是不是月初(1号) @:param date_time datetime类型 @:return date_time所在月的1号 """ def __first_day_of_month(self, date_time): self.logger.info("判断{}是否是月初".format(date_time)) return (date_time + datetime.timedelta(days=-date_time.day + 1)).replace(hour=0, minute=0, second=0, microsecond=0)
2.获取当月的天数,用于计算月末日期
_, current_month_days = calendar.monthrange(start_date.year, start_date.month)
_, current_month_days = calendar.monthrange(2018, 09)
计算月末日期
current_end_date_time = start_date + datetime.timedelta(days=current_month_days-1)
3.获取传入的日期为当年第几周
current_start_time = datetime.date(2018,09,17) current_start_time.isocalendar()[1] # 返回的数字便是周数
4.获取传入的日期为星期几(也就是当周的第几天)
start_date.weekday() # 返回0-6表示周一到周日
其他的待补充。。。
Your code.
Your code.
Your code.
Your code.
Your code.
Your code.
Your code.