欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python本地时间与UTC时间转换

程序员文章站 2024-01-23 14:47:04
...

说明:python本地时间与UTC时间转换,程序中常用于日志或生成文件命名,待补充完善。
参考小例

# -*- coding: utf-8 -*-

import time
import datetime


class TimeShift:
    def __init__(self):
        pass

    def get_utctime(self) -> datetime.datetime:
        utc_time = datetime.datetime.utcfromtimestamp(time.time())
        return utc_time

    def utctime_format(self) -> str:
        '''
        作用:datetime.datetime格式化成字符串,可用于文件命名
        :return: str
        '''
        utc_fmt = self.get_utctime().strftime("%Y%m%d%H%M%S")
        return utc_fmt

    def get_localtime(self):
        local_time = datetime.datetime.now()
        return local_time

    def localtime_format(self):
        local_fmt = self.get_localtime().strftime("%Y%m%d%H%M%S")
        return local_fmt

    def utc2local(self, utc_st) -> datetime.datetime:
        '''
        作用:将utc时间转换成本地时间
        :return: 返回本地时间
        '''
        now_stamp = time.time()
        local_time = datetime.datetime.fromtimestamp(now_stamp)
        utc_time = datetime.datetime.utcfromtimestamp(now_stamp)
        offset = local_time - utc_time
        local_st = utc_st + offset
        return local_st

    def local2utc(self, local_st) -> datetime.datetime:
        '''
        作用:将本地时间转成utc时间
        :return: 返回utc时间
        '''
        time_struct = time.mktime(local_st.timetuple())
        utc_st = datetime.datetime.utcfromtimestamp(time_struct)
        return utc_st

    def print_sep(self, num=50):
        line_sep = "-" * num
        print(line_sep)

    def main(self):
        utc2local = self.utc2local(self.get_utctime())
        local2utc = self.local2utc(self.get_localtime())
        print("utc time: %s" % self.get_utctime())
        print("local time: %s" % self.get_localtime())
        self.print_sep(40)
        print("utc2local time: %s" % utc2local)
        print("local2utc time: %s" % local2utc)
        self.print_sep(40)
        print("utctime format time: %s" % self.utctime_format())
        print("localtime format time: %s" % self.localtime_format())


if __name__ == '__main__':
    timeshift = TimeShift()
    timeshift.main()

返回结果:

utc time: 2020-04-19 03:09:34.915714
local time: 2020-04-19 11:09:34.915714
----------------------------------------
utc2local time: 2020-04-19 11:09:34.915714
local2utc time: 2020-04-19 03:09:34
----------------------------------------
utctime format time: 20200419030934
localtime format time: 20200419110934
相关标签: Python基础