简体   繁体   English

通过 Python,当系统时钟是 UTC 时,根据 DST 调整本地时间? 必须使用时间模块而不是日期时间

[英]Via Python, get local time adjusted for DST, when system clock is UTC? Must use time module not datetime

Via Python, get local time adjusted for DST, when system clock is UTC?通过 Python,当系统时钟是 UTC 时,根据 DST 调整本地时间? Must use time module not datetime.必须使用时间模块而不是日期时间。

Using time.localtime() for returns UTC not local time.使用 time.localtime() 返回 UTC 而不是本地时间。 So how do you use time module in python to get DST adjusted local time when system clock is UTC?那么当系统时钟为UTC时,如何在python中使用time模块来获得DST调整后的本地时间?

I assume by "system time is in UTC" you mean "the environment is not configured to use a time zone".我假设“系统时间为 UTC”是指“环境未配置为使用时区”。 You can set the time zone manually from Python.您可以从 Python 手动设置时区。 ( bash example) bash示例)

import os
import time

os.environ['TZ'] = 'Asia/Tokyo'
time.tzset()
print(time.localtime())
# => time.struct_time(tm_year=2021, tm_mon=7, tm_mday=16, tm_hour=9, tm_min=42, tm_sec=58, tm_wday=4, tm_yday=197, tm_isdst=0)

os.environ['TZ'] = 'US/Alaska'
time.tzset()
print(time.localtime())
# => time.struct_time(tm_year=2021, tm_mon=7, tm_mday=15, tm_hour=16, tm_min=42, tm_sec=58, tm_wday=3, tm_yday=196, tm_isdst=1)

If your environment is limited, you may not have the timezone info files at /usr/share/zoneinfo .如果您的环境有限,您可能没有/usr/share/zoneinfo的时区信息文件。 You can either copy the files you will need (eg /usr/share/zoneinfo/Asia/Tokyo ), or you may define your TZ manually.您可以复制您需要的文件(例如/usr/share/zoneinfo/Asia/Tokyo ),或者您可以手动定义您的TZ See time.tzset() for more details.有关更多详细信息,请参阅time.tzset()

Obviously, you can also set the TZ environment variable before you start your program, in which case importing os will not be necessary:显然,您也可以在启动程序之前设置TZ环境变量,在这种情况下,导入os将是不必要的:

TZ=Asia/Tokyo python ....
TZ=US/Alaska python ....

or或者

export TZ=Asia/Tokyo
python ...

export TZ=US/Alaska
python ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM