最可靠方式是用 timedatectl 设置时区:sudo timedatectl set-timezone Asia/Shanghai,它自动更新 /etc/localtime 并通知系统服务;手动复制或仅改环境变量易导致日志、Python 等仍用 UTC。

直接用 timedatectl 设置时区最可靠
Linux 现代发行版(如 Ubuntu 20.04+、CentOS 8+、Debian 10+)默认使用 systemd,timedatectl 是唯一推荐方式。它会自动同步更新 /etc/localtime 软链接,并通知内核和用户空间服务,避免手动改文件后部分程序仍读错时区。
执行以下命令即可设为中国标准时间(CST,即 Asia/Shanghai):
sudo timedatectl set-timezone Asia/Shanghai
验证是否生效:
timedatectl status | grep "Time zone"
输出应类似:Time zone: Asia/Shanghai (CST, +0800)
- 别用
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime手动覆盖——这会绕过systemd管理,某些服务(如rsyslog、journalctl)可能缓存旧时区 -
Asia/Shanghai是标准名称,不是China/Beijing或PRC(后者虽存在但已弃用) - 如果提示
No such file or directory,说明系统未安装时区数据包,Ubuntu/Debian 运行sudo apt install tzdata,RHEL/CentOS 运行sudo dnf install glibc-common
旧系统或容器里没有 timedatectl 怎么办
某些精简系统(如 Alpine Linux 容器、嵌入式 BusyBox 环境)不带 systemd,只能手动配置。核心是两件事:让 C 库读到正确时区,让 shell 环境变量生效。
先确认时区文件存在:
ls /usr/share/zoneinfo/Asia/Shanghai
然后建立软链接并设置环境变量:
sudo ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime<br>echo "TZ=Asia/Shanghai" | sudo tee -a /etc/profile.d/tz.sh
最后在当前 shell 生效:
export TZ=Asia/Shanghai
- 仅改
/etc/localtime不够:glibc 会读它,但 Bash/Python 等语言可能优先查TZ环境变量 - 容器中不要用
date -s改系统时间——宿主机时间通常不允许被容器修改,且改了也无效 - Alpine 用户注意:
tzdata包需显式安装:apk add tzdata,否则/usr/share/zoneinfo为空
为什么 date 显示对了,但日志或 Python 脚本还是 UTC 时间
常见于服务以非交互式方式启动(如 systemd service、cron job),它们不会自动加载 /etc/profile 或 /etc/environment 中的 TZ 变量。
- systemd 服务:在 unit 文件中加
Environment=TZ=Asia/Shanghai - cron 任务:在 crontab 开头添加
TZ=Asia/Shanghai行,或在脚本开头写export TZ=Asia/Shanghai - Python 脚本:不要依赖
time.localtime(),改用datetime.now().astimezone()或显式传入zoneinfo.ZoneInfo("Asia/Shanghai")(Python 3.9+) - Java 应用:JVM 启动参数加
-Duser.timezone=Asia/Shanghai,否则默认读 host 的/etc/timezone或 fallback 到 UTC
检查 NTP 同步状态,避免时区正确但时间本身不准
时区设对了,不代表时间就准。中国不参与国际 NTP 公共池(pool.ntp.org),国内常用阿里云、腾讯云或中科院的 NTP 服务器。
查看同步状态:
timedatectl status
若显示 NTP service: inactive,启用并配置国内源:
sudo timedatectl set-ntp true<br>sudo systemctl restart systemd-timesyncd
然后编辑配置(Ubuntu/Debian):
sudo nano /etc/systemd/timesyncd.conf
取消注释并修改为:
NTP=ntp.aliyun.com ntp.tencent.com
-
systemd-timesyncd是轻量级 SNTP 客户端,比ntpd更适合桌面/云服务器;如需高精度,换用chrony并配置相同 NTP 源 - 防火墙要放行 UDP 123 端口,否则同步失败但无明显报错
- 某些云厂商(如 AWS EC2)禁用外部 NTP,强制使用其内部时间源,此时应配置
169.254.169.123


















