概述
# -*- 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()
最后
以上就是怕孤单草莓为你收集整理的python localtime 与utc时间差5分钟_Python本地时间与UTC时间转换的全部内容,希望文章能够帮你解决python localtime 与utc时间差5分钟_Python本地时间与UTC时间转换所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复