You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python Tkinter时钟的UTC时区切换为华沙时区显示?

如何将Tkinter时钟程序从UTC时区切换为华沙时区?

我用Python的Tkinter库开发了一个时钟程序,但目前默认显示UTC时区的时间,希望将其切换为华沙时区的时间。以下是当前代码:

from tkinter import *
from time import *


def update():
    time_string = strftime("%H:%M:%S")
    time_label.config(text=time_string)
    
    day_string = strftime("%A")
    day_label.config(text=day_string)

    date_string = strftime("%B %d, %Y")
    date_label.config(text=date_string)
    
    window.after(1000,update)

window = Tk()

time_label = Label(window,font=("Arial",50),fg="#0000ff",bg="white")
time_label.pack()

day_label = Label(window,font=("Comic sans",25,"bold"))
day_label.pack()

date_label = Label(window,font=("Comic Sans MS",30))
date_label.pack()

update()

window.mainloop()

时钟界面截图:
时钟界面截图


解决方案

Python标准库的time.strftime默认依赖系统本地时区或UTC,要指定华沙时区(含夏令时自动切换),可以用以下两种方法:

方法1:使用Python 3.9+自带的zoneinfo(无需额外安装)

替换原代码中的time模块为datetime和zoneinfo,直接获取华沙时区的时间:

from tkinter import *
from datetime import datetime
from zoneinfo import ZoneInfo

def update():
    # 获取华沙时区的当前时间
    warsaw_time = datetime.now(tz=ZoneInfo("Europe/Warsaw"))
    
    time_string = warsaw_time.strftime("%H:%M:%S")
    time_label.config(text=time_string)
    
    day_string = warsaw_time.strftime("%A")
    day_label.config(text=day_string)

    date_string = warsaw_time.strftime("%B %d, %Y")
    date_label.config(text=date_string)
    
    window.after(1000, update)

window = Tk()

time_label = Label(window, font=("Arial",50), fg="#0000ff", bg="white")
time_label.pack()

day_label = Label(window, font=("Comic sans",25,"bold"))
day_label.pack()

date_label = Label(window, font=("Comic Sans MS",30))
date_label.pack()

update()

window.mainloop()

方法2:使用pytz库(适用于Python 3.9以下版本)

先安装依赖:

pip install pytz

然后修改代码:

from tkinter import *
from datetime import datetime
import pytz

def update():
    # 指定华沙时区
    warsaw_tz = pytz.timezone("Europe/Warsaw")
    warsaw_time = datetime.now(warsaw_tz)
    
    time_string = warsaw_time.strftime("%H:%M:%S")
    time_label.config(text=time_string)
    
    day_string = warsaw_time.strftime("%A")
    day_label.config(text=day_string)

    date_string = warsaw_time.strftime("%B %d, %Y")
    date_label.config(text=date_string)
    
    window.after(1000, update)

window = Tk()

time_label = Label(window, font=("Arial",50), fg="#0000ff", bg="white")
time_label.pack()

day_label = Label(window, font=("Comic sans",25,"bold"))
day_label.pack()

date_label = Label(window, font=("Comic Sans MS",30))
date_label.pack()

update()

window.mainloop()

两种方法都会自动处理华沙时区的夏令时切换,确保时间显示准确。


内容的提问来源于stack exchange,提问作者WikInf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 14:14:54