# -*- coding: UTF-8 -*- import calendar from datetime import timedelta from django.utils import timezone def timestamp_of(d): if hasattr(d, 'isoformat'): return calendar.timegm(d.utctimetuple()) return None def now(): return timezone.localtime(timezone.now()) def midnight(): return now().replace(hour=0, minute=0, second=0, microsecond=0) def is_today(tme): if day_of(tme) != day_of(midnight()): return False return True def current_time_n(n): return now() - timedelta(days=n) def day_n(n): """Midnight of N days ago.""" return midnight() - timedelta(days=n) def day_of(d): """Returns date part.""" return str(d.date()) def midnight_of(d): """ Args: d : datetime object Return: Midnight of datetime. """ d = timezone.localtime(d) return d.replace(hour=0, minute=0, second=0, microsecond=0) def day_start(date): """返回 date 这天的开始时间 Args: date: `Datetime` 对象 Returns: 返回 date 这天的开始时间(0 点),`Datetime` 对象 """ return timezone.localtime(date).replace(hour=0, minute=0, second=0, microsecond=0) def week_start(date): """返回 date 这天所在周的开始时间 Args: date: `Datetime` 对象 Returns: 返回 date 这天所在周开始时间(周一),`Datetime` 对象 """ return timezone.localtime(date) + dateutil.relativedelta.relativedelta( weekday=dateutil.relativedelta.MO(-1), hour=0, minute=0, second=0, microsecond=0 ) def month_start(d): """返回 date 这天所在月的开始时间 Args: date: `Datetime` 对象 Returns: 返回 date 这天所在月的开始时间(1号),`Datetime` 对象 """ return timezone.localtime(d) + dateutil.relativedelta.relativedelta( day=1, hour=0, minute=0, second=0, microsecond=0 ) def month_end(d): """返回 date 这天所在月的结束时间,即最后一天的 23:59:59 Args: data: `Datetime` 对象 Returns: 返回 date 这天所在月的最后一天的 23:59:59 的时间 """ start = month_start(d) month_days = calendar.monthrange(start.year, start.month)[1] return start + timedelta(days=month_days, seconds=-1) def year_start(d): """返回 date 这天所在年的开始时间 Args: date: `Datetime` 对象 Returns: 返回 date 这天所在年的开始时间(1月 1号),`Datetime` 对象 """ return timezone.localtime(d) + dateutil.relativedelta.relativedelta( month=1, day=1, hour=0, minute=0, second=0, microsecond=0 )