时间相关

import time
import datetime


class TimeAbout():

    def TimeStamp(self, **kwargs):
        _ = self
        """
        获取时间戳
        """
        t = kwargs.get('time')
        if t is None:
            return int(time.time())
        else:
            # 字符类型的时间
            # t = '2013-10-10 23:40:00'
            # 转为时间数组
            try:
                timeArray = time.strptime(t, "%Y-%m-%d %H:%M:%S")
            except:
                timeArray = time.strptime(t, "%Y-%m-%d")
            # print(timeArray)
            # timeArray可以调用tm_year等
            # print(timeArray.tm_year)  # 2013
            # 转为时间戳
            timeStamp = int(time.mktime(timeArray))
            # print(timeStamp)  # 1381419600
            return timeStamp

    def StyleTime(self, timeStamp):
        _ = self
        """
        获取时间
        # 使用time
        timeStamp = 1381419600
        timeArray = time.localtime(timeStamp)
        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
        print(otherStyleTime)  # 2013--10--10 23:40:00
        # 使用datetime
        timeStamp = 1381419600
        dateArray = datetime.datetime.fromtimestamp(timeStamp)
        otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
        print(otherStyleTime)  # 2013--10--10 23:40:00
        # 使用datetime,指定utc时间,相差8小时
        timeStamp = 1381419600
        dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
        otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
        print(otherStyleTime)  # 2013--10--10 15:40:00
        """
        timeArray = time.localtime(timeStamp)
        otherStyleTime = time.strftime("%Y-%m-%d", timeArray)
        return otherStyleTime

    def get_local_time(self):
        _ = self
        """
        获取当前准确时间
        """
        d = time.localtime()
        tm_year = str(d.tm_year)
        tm_mon = str(d.tm_mon) if len(str(d.tm_mon)) == 2 else '0' + str(d.tm_mon)
        tm_mday = str(d.tm_mday) if len(str(d.tm_mday)) == 2 else '0' + str(d.tm_mday)
        tm_hour = str(d.tm_hour) if len(str(d.tm_hour)) == 2 else '0' + str(d.tm_hour)
        tm_min = str(d.tm_min) if len(str(d.tm_min)) == 2 else '0' + str(d.tm_min)
        tm_sec = str(d.tm_sec) if len(str(d.tm_sec)) == 2 else '0' + str(d.tm_sec)
        today = tm_year + '-' + tm_mon + '-' + tm_mday + ' ' + tm_hour + ':' + tm_min + ':' + tm_sec

        return today

    def get_today(self):
        _ = self
        """
        获取昨天日期
        """
        today = self.get_local_time().split(' ')[0]
        return today

    def get_yesterday(self):
        _ = self
        """
        获取昨天日期
        """
        today = self.get_today()
        yesterday = self.StyleTime(self.TimeStamp(time=today) - 60 * 60 * 12)

        return yesterday

 

上一篇:Oralce数据回滚


下一篇:将Excel数据转换为Java可识别时间(Date、Timestamp)