# coding=utf8 from __future__ import unicode_literals, absolute_import, print_function import datetime import time import pytz from django.conf import settings from django.utils import timezone def get_timestamp_epoch(the_time): if the_time is None: return None if isinstance(the_time, str): try: the_time = datetime.datetime.strptime(the_time, "%Y-%m-%d %H:%M:%S") except ValueError: raise ValueError('time string must in <%Y-%m-%d %H:%M:%S> format') if isinstance(the_time, datetime.datetime): pass elif isinstance(the_time, datetime.date): # TODO: 是这样算的么? the_time = datetime.datetime( the_time.year, the_time.month, the_time.day) else: raise TypeError( "datetime.datetime or datetime.date expected. [%s]" % type(the_time)) return int((the_time - datetime.datetime.fromtimestamp(0)).total_seconds()) def get_timestamp(the_time): if the_time is None: return None return get_timestamp_epoch(the_time) + 8 * 3600 def get_datetime(the_time): return datetime.datetime.utcfromtimestamp(the_time) def get_timestamp_or_none(the_time): return get_timestamp(the_time) if the_time is not None else None def week_monday(date): """ 返回date所属周的周一 """ return add_day(date, -date.isoweekday() + 1) def get_monday(day=None): """ 返回输入日期的当星期的星期一的日期 :param day: 输入日期 :return: 输入日期的星期的星期一 """ if not day: day = datetime.date.today() return week_monday(day) def get_humanize_datetime(d): """humanize datetime """ now = datetime.datetime.now() if d.year == now.year: if d.month == now.month: if d.day == now.day: return u'今天' else: return u'{}天前'.format(now.day - d.day) else: return d.strftime('%m-%d') else: return d.strftime('%Y-%m-%d') def get_seconds_left_to_end_of_day(): now = timezone.now() end_of_day = datetime.datetime.combine(now, datetime.time.max) time_delta = end_of_day - now return int(time_delta.total_seconds()) def add_month(dt, n): return datetime.date( dt.year + (dt.month + n - 1) / 12, (dt.month + n) % 12 or 12, dt.day, ) def add_day(dt, n): return dt + datetime.timedelta(days=n) def tzlc(dt, truncate_to_sec=True): if dt is None: return None if truncate_to_sec: dt = dt.replace(microsecond=0) return pytz.timezone(settings.TIME_ZONE).localize(dt) def ts_now_as_score(): return int(time.mktime(timezone.now().timetuple())) MIN_TIME = tzlc(datetime.datetime.utcfromtimestamp(0)) MAX_TIME = tzlc(datetime.datetime.utcfromtimestamp(2147483647))