python时间处理相关方法汇总。

# encoding:utf-8
import time
import datetime
import calendar
from dateutil import parser
from datetime import timedelta


class TimeCore:
    @classmethod
    def local_format(self, fmt='%Y-%m-%d %H:%M:%S'):
        '''获取当前时间格式化
        '''
        return datetime.datetime.now().strftime(fmt)

    @classmethod
    def local_timestamp(self):
        '''获取当前时间戳
        '''
        return int(time.time())

    @classmethod
    def local_timestamp_m(self):
        '''获取当前时间戳(毫秒)
        '''
        return int(time.time()*1000)

    @classmethod
    def timestamp(self, string):
        '''获取时间戳   str——>int
        '''
        return int(parser.parse(string).timestamp())

    @classmethod
    def parse(self, string):
        '''任意格式的字符串转成时间     str——>datetime
        '''
        return parser.parse(string)

    @classmethod
    def add_days(self, string, days):
        '''时间累加(天)
        '''
        return self.parse(string)+datetime.timedelta(days=days)

    @classmethod
    def add_hours(self, string, hours):
        '''时间累加(小时)
        '''
        return self.parse(string)+datetime.timedelta(hours=hours)

    @classmethod
    def add_minutes(self, string, minutes):
        '''时间累加(分钟)
        '''
        return self.parse(string)+datetime.timedelta(minutes=minutes)

    @classmethod
    def add_seconds(self, string, seconds):
        '''时间累加(秒)
        '''
        return self.parse(string)+datetime.timedelta(seconds=seconds)

    @classmethod
    def timestamp_add_days(self, timestamp, days):
        '''时间累加(天)
        '''
        return self.parse_timestamp(timestamp)+datetime.timedelta(days=days)

    @classmethod
    def timestamp_add_hours(self, timestamp, hours):
        '''时间累加(小时)
        '''
        return self.parse_timestamp(timestamp)+datetime.timedelta(hours=hours)

    @classmethod
    def timestamp_add_minutes(self, timestamp, minutes):
        '''时间累加(分钟)
        '''
        return self.parse_timestamp(timestamp)+datetime.timedelta(minutes=minutes)

    @classmethod
    def timestamp_add_seconds(self, timestamp, seconds):
        '''时间累加(秒)
        '''
        return self.parse_timestamp(timestamp)+datetime.timedelta(seconds=seconds)

    @classmethod
    def parse_timestamp(self, timestamp):
        '''时间戳转成时间(精确到秒)int——>datetime
        '''
        time_array = time.localtime(timestamp)
        y, m, d, h, i, s = time_array[0:6]
        return datetime.datetime(y, m, d, h, i, s)

    @classmethod
    def parse_timestamp2(self, timestamp):
        '''时间戳转成时间(精确到天)int——>datetime
        '''
        time_array = time.localtime(timestamp)
        y, m, d, h, i, s = time_array[0:6]
        return datetime.datetime(y, m, d)

    @classmethod
    def parse_timestamp_fmt(self, timestamp, fmt='%Y-%m-%d %H:%M:%S'):
        '''时间戳转成时间(精确到秒)int——>str
        '''
        time_array = time.localtime(timestamp)
        return time.strftime(fmt, time_array)

    @classmethod
    def parse_timestamp_fmt0(self, timestamp, fmt='%Y-%m-%d-%H:%M'):
        '''时间戳转成时间(精确到分钟)int——>str
        '''
        time_array = time.localtime(timestamp)
        return time.strftime(fmt, time_array)

    @classmethod
    def parse_timestamp_fmt1(self, timestamp, fmt='%Y%m%d%H'):
        '''时间戳转成时间(精确到小时)int——>str
        '''
        time_array = time.localtime(timestamp)
        return time.strftime(fmt, time_array)

    @classmethod
    def parse_timestamp_fmt2(self, timestamp, fmt='%Y-%m-%d'):
        '''时间戳转成时间(精确到天)int——>str
        '''
        time_array = time.localtime(timestamp)
        return time.strftime(fmt, time_array)

    @classmethod
    def parse_timestamp_fmt3(self, timestamp, fmt='%Y-%m'):
        '''时间戳转成时间(精确到月)int——>str
        '''
        time_array = time.localtime(timestamp)
        return time.strftime(fmt, time_array)

    @classmethod
    def time_desc(self, date_time):
        '''商品描述
        '''
        now = datetime.datetime.now()
        seconds = (now-date_time).total_seconds()
        if seconds < 60:
            return '刚刚'
        elif seconds < 3600:
            return '%s分钟前' % (int(seconds//60))
        elif seconds < 3600*24:
            return '%s小时前' % (int(seconds//3600))
        return date_time.strftime('%Y-%m-%d %H:%M:%S')

    @classmethod
    def this_isoweek(cls):
        # 按照日历划分的"本周"
        today = datetime.date.today()
        dayscount = datetime.timedelta(days=today.isoweekday()-1)
        dayfrom = today - dayscount
        days = []
        for day in range(7):
            sixdays = datetime.timedelta(days=day)
            dayto = dayfrom + sixdays
            days.append(dayto)
        return days

    @classmethod
    def this_isoweek_monday(cls):
        # 按照日历划分的"本周"的"周一"
        today = datetime.date.today()
        dayscount = datetime.timedelta(days=today.isoweekday()-1)
        monday = today - dayscount
        return monday

    @classmethod
    def last_isoweek_monday(cls, today=None):
        if not today:
            # 按照日历划分的"本周"的"周一"
            today = datetime.date.today()
        dayscount = datetime.timedelta(days=today.isoweekday() - 1 + 7)
        monday = today - dayscount
        return monday

    @classmethod
    def datetime_to_timestamp(cls, _date):
        '''将datetime转化为时间戳  datetime ——> int
        '''
        return int(time.mktime(_date.timetuple()))

    @classmethod
    def datetime_to_str(cls, datetime1, fmt='%Y-%m-%d'):
        '''获取当前时间格式化
        '''
        return datetime1.strftime(fmt)

    @classmethod
    def datetime_to_str_hour(cls, datetime1, fmt='%Y%m%d%H'):
        '''获取当前时间格式化
        '''
        return datetime1.strftime(fmt)

    @classmethod
    def isoweek_sunday(cls, monday):
        # 根据周一时间戳获取相对应周日的时间戳
        monday_str = cls.parse_timestamp_fmt(monday)
        sunday_date = cls.add_days(monday_str, days=6)
        sunday = cls.datetime_to_timestamp(sunday_date)
        return sunday

    @classmethod
    def one_iosweek_monday(cls, tsp, _format="timestamp"):
        # 根据时间戳获取该周的周一
        _date = cls.parse_timestamp(tsp)
        # 根据datetime获取该周的周一
        dayscount = datetime.timedelta(days=_date.isoweekday() - 1)
        monday = _date - dayscount
        if _format == "timestamp":
            return cls.datetime_to_timestamp(monday.date())
        else:
            return monday.date()

    @classmethod
    def get_month_start(cls, timestamp):
        """
        :param timestamp:
        :return:本月第一天日期和本月最后一天日期的时间戳
        """
        date = cls.parse_timestamp_fmt2(timestamp)
        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' % (year, month)
        end_date = '%s-%s-%s' % (year, month, end)
        start_timestamp = cls.timestamp(start_date)
        end_timestamp = cls.timestamp(end_date)
        return start_timestamp, end_timestamp

    @classmethod
    def getYearMonthsDay(cls):
        '''获取本月最后一天
        '''
        # 获取当前年份
        thisYear = datetime.date.today().year
        # 获取当前月份
        thisMonth = datetime.date.today().month
        # 获取当前天
        # thisDay = datetime.date.today().day
        result = []
        for x in range(1, thisMonth + 1):
            monthRange = calendar.monthrange(thisYear, x)[1]
            # startDay = str(thisYear) + "-" + str(x).zfill(2) + "-01"
            endDay = str(thisYear) + "-" + str(x).zfill(2) + "-"
            endDay = endDay + str(monthRange).zfill(2)
            # result[str(x)] = [startDay, endDay]
            result.append(endDay)
        return result

    @classmethod
    def getOneYearMonthLastDay(cls, month_ago):
        '''获取一年内几个月前的最后一天的列表
        '''
        # 获取当前年份
        thisYear = datetime.date.today().year
        # 获取当前月份
        thisMonth = datetime.date.today().month
        # 获取当前天
        # thisDay = datetime.date.today().day
        result = []

        if thisMonth - month_ago < 0:
            thisYear -= 1
            for x in range(thisMonth - month_ago + 12, 13):
                monthRange = calendar.monthrange(thisYear, x)[1]
                # startDay = str(thisYear) + "-" + str(x).zfill(2) + "-01"
                endDay = str(thisYear) + "-" + str(x).zfill(2) + "-"
                endDay = endDay + str(monthRange).zfill(2)
                # result[str(x)] = [startDay, endDay]
                result.append(endDay)
            thisYear += 1
            for x in range(1, thisMonth):
                monthRange = calendar.monthrange(thisYear, x)[1]
                # startDay = str(thisYear) + "-" + str(x).zfill(2) + "-01"
                endDay = str(thisYear) + "-" + str(x).zfill(2) + "-"
                endDay = endDay + str(monthRange).zfill(2)
                # result[str(x)] = [startDay, endDay]
                result.append(endDay)
        else:
            for x in range(thisMonth - month_ago, thisMonth):
                monthRange = calendar.monthrange(thisYear, x)[1]
                # startDay = str(thisYear) + "-" + str(x).zfill(2) + "-01"
                endDay = str(thisYear) + "-" + str(x).zfill(2) + "-"
                endDay = endDay + str(monthRange).zfill(2)
                # result[str(x)] = [startDay, endDay]
                result.append(endDay)
        return result

    @classmethod
    def days_ago(cls, timestamp, day):
        '''输入时间戳(int)获取几天前的时间str
        '''
        day_datetime = TimeCore.parse_timestamp2(timestamp)
        day_ago_datetime = day_datetime - datetime.timedelta(days=day)
        day_ago_stamp = int(datetime.datetime.timestamp(day_ago_datetime))
        return cls.parse_timestamp_fmt2(day_ago_stamp)  # 返回日期

    @classmethod
    def one_months_ago(cls, timestamp):
        '''输入时间戳(int)获取上一个月份的str
        return eg:2021-02
        '''
        day_datetime = TimeCore.parse_timestamp2(timestamp)
        day_ago_datetime = day_datetime - datetime.timedelta(days=1)
        day_ago_stamp = int(datetime.datetime.timestamp(day_ago_datetime))
        return cls.parse_timestamp_fmt3(day_ago_stamp)  # 返回日期

    @classmethod
    def every_weeks(cls, m, n):
        # 最近两个月的每周起止时间
        # 当前周前m周到后n周的每周开始日期和结束日期
        # now当前日期
        now = cls.parse_timestamp2(cls.local_timestamp()).date()
        period_list = []
        for x in range(m, n + 1):
            if x < 0:
                lDay = now - timedelta(days=now.weekday() + (7 * abs(x)))
            # 本周
            elif x == 0:
                lDay = now - timedelta(days=now.weekday())
            # 后几周
            else:
                lDay = now + timedelta(days=(7 - now.weekday()) + 7 * (x - 1))
            rDay = lDay + timedelta(days=6)
            start_time = time.strptime(str(lDay), "%Y-%m-%d")
            start_time = int(time.mktime(start_time))
            end_time = time.strptime(str(rDay), "%Y-%m-%d")
            end_time = int(time.mktime(end_time))
            # period = [cls.parse_timestamp_fmt2(
            #     start_time), cls.parse_timestamp_fmt2(end_time)]
            period = cls.parse_timestamp_fmt2(end_time)
            period_list.append(period)
        return period_list

    @classmethod
    def get_last_day(cls):
        """获取昨日的日期str。
        """
        now = cls.local_timestamp()
        date = cls.parse_timestamp_fmt2(now)
        zero_timestamp = cls.timestamp(date)
        lastday = cls.days_ago(zero_timestamp, 0.5)
        return lastday

    @classmethod
    def get_week_num(cls, timestamp):
        """
        1:周一,2:周二
        """
        date = str(timestamp)
        ltime = time.localtime(int(date))
        dateymd = time.strftime("%Y-%m-%d", ltime)
        week_num = (datetime.datetime.strptime(
            dateymd, "%Y-%m-%d").weekday()+1)
        return week_num

    @classmethod
    def get_time_interval(cls, timestamp):
        """
        获取时间段。0:0-1点 1:1-2点 …… 23:23-24点
        """
        # 获取小时信息。
        hour = time.localtime(timestamp).tm_hour
        return hour

    @classmethod
    def get_today_last_timestamp(cls):
        date_now = cls.parse_timestamp_fmt2(
            cls.local_timestamp())
        set_time = cls.parse(date_now+' 23:59:58')
        set_time_stamp = TimeCore.datetime_to_timestamp(set_time)
        return set_time_stamp

    @classmethod
    def get_oneday_last_timestamp(cls, date_now):
        '''获取指定时间天的最后一个'''
        set_time = cls.parse(date_now+' 23:59:58')
        set_time_stamp = TimeCore.datetime_to_timestamp(set_time)
        return set_time_stamp
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值