最近有许多数据库查询操作,为了更准确地定位目标数据,所以大量使用时间戳进行筛选,每次都去在线开网页有点烦,加之最近在看《Python基础教程》,遂搞一个小工具。
import datetime
import time
from tkinter import *
import pytz
def local_to_utc(ts, time_format=r'%Y-%m-%d %H:%M:%S'):
time_zone = pytz.timezone('Asia/Shanghai')
# 首先将本地时间戳转化为时间元组,用strftime格式化成字符串, localtime入参为秒
time_str = time.strftime(time_format, time.localtime(ts / 1000))
# 将字符串用strptime 转为为datetime中 datetime格式
dt = datetime.datetime.strptime(time_str, time_format)
utc_dt = dt.astimezone(time_zone) # astimezone切换为 utc 时区
return utc_dt.strftime(time_format)
def calculate_timestamp():
try:
timestamp_temp = int(timestamp.get())
timestamp_value = local_to_utc(timestamp_temp)
except Exception:
timestamp_value = '转换失败'
result.config(state='normal')
result.delete(0, END)
result.insert(END, timestamp_value)
result.config(state='readonly')
def calculate_format_time():
try:
target_time = time.strptime(now_time.get(), '%Y-%m-%d %H:%M:%S')
target_timestamp = int(time.mktime(target_time) * 1000)
except Exception:
target_timestamp = '转换失败'
result_timestamp.config(state='normal')
result_timestamp.delete(0, END)
result_timestamp.insert(END, target_timestamp)
result_timestamp.config(state='readonly')
top = Tk()
top.title("timestamp calculator")
timestamp_label = Label(top, text="时间戳(ms)")
timestamp_label.grid(row=0, column=0)
timestamp = Entry()
timestamp.grid(row=0, column=1)
calculate_btn = Button(text='转换 >>', command=calculate_timestamp)
calculate_btn.grid(row=0, column=2)
result_label = Label(top, text="北京时间")
result_label.grid(row=0, column=3)
result = Entry()
result.grid(row=0, column=4)
time_label = Label(top, text="时间")
time_label.grid(row=1, column=0)
now_time = Entry()
now_time.grid(row=1, column=1)
now_time.insert(END, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
calculate_btn_2rd = Button(text='转换 >>', command=calculate_format_time)
calculate_btn_2rd.grid(row=1, column=2)
result_timestamp_label = Label(top, text="时间戳(ms)")
result_timestamp_label.grid(row=1, column=3)
result_timestamp = Entry()
result_timestamp.grid(row=1, column=4)
mainloop()