python 带时区的日期格式化方式

Wed, 23 Oct 2019 21:12:01 +0800

Wed, 23 Oct 2019 06:08:37 +0000 (GMT)

Fri, 11 Oct 2019 12:42:07 +0800 (CST)

Wed, 23 Oct 2019 06:08:37 +0000 (UTC)

几种不同的日期格式化方式,不同的时区时间转换成北京时间,也就是东八区的时间,注意的是后面的时区表示方式,

    def getTimeStamp(self, date):
        result = re.search(r"[\-\+]\d+", date)
        if result:
            time_area = result.group()
            symbol = time_area[0]
            offset = int(time_area[1]) + int(time_area[2])
            if symbol == "+":
                format_str = '%a, %d %b %Y %H:%M:%S '+ time_area
                if "UTC" in date:
                    format_str = '%a, %d %b %Y %H:%M:%S '+ time_area+ ' (UTC)'
                if "GMT" in date:
                    format_str = '%a, %d %b %Y %H:%M:%S ' + time_area + ' (GMT)'
                if "CST" in date:
                    format_str = '%a, %d %b %Y %H:%M:%S ' + time_area + ' (CST)'
                utcdatetime = time.strptime(date, format_str)
                tempsTime = time.mktime(utcdatetime)
                tempsTime = datetime.datetime.fromtimestamp(tempsTime)
                if offset > 8:
                    offset = offset -8
                tempsTime = tempsTime + datetime.timedelta(hours=offset)
                localtimestamp = tempsTime.strftime("%Y-%m-%d")
            else:
                format_str = '%a, %d %b %Y %H:%M:%S ' + time_area
                utcdatetime = time.strptime(date, format_str)
                tempsTime = time.mktime(utcdatetime)
                tempsTime = datetime.datetime.fromtimestamp(tempsTime)
                tempsTime = tempsTime + datetime.timedelta(hours=(offset + 8))
                localtimestamp = tempsTime.strftime("%Y-%m-%d")
        return localtimestamp

 

你可能感兴趣的:(python)