Via Python, get local time adjusted for DST, when system clock is UTC? Must use time module not datetime.
Using time.localtime() for returns UTC not local time. So how do you use time module in python to get DST adjusted local time when system clock is UTC?
I assume by "system time is in UTC" you mean "the environment is not configured to use a time zone". You can set the time zone manually from Python. ( bash
example)
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
. You can either copy the files you will need (eg /usr/share/zoneinfo/Asia/Tokyo
), or you may define your TZ
manually. See time.tzset()
for more details.
Obviously, you can also set the TZ
environment variable before you start your program, in which case importing os
will not be necessary:
TZ=Asia/Tokyo python ....
TZ=US/Alaska python ....
or
export TZ=Asia/Tokyo
python ...
export TZ=US/Alaska
python ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.