时间戳转换工具

最近有许多数据库查询操作,为了更准确地定位目标数据,所以大量使用时间戳进行筛选,每次都去在线开网页有点烦,加之最近在看《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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kiba_zwei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值