Python time
说明: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()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 72
返回结果:
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!