Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

datetime - Converting time zone in Python


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming your string represents Unix time / seconds since 1970-1-1, it refers to UTC. You can convert it to datetime like

from datetime import datetime, timezone

s = '1346114717'
dt = datetime.fromtimestamp(int(s), tz=timezone.utc)

print(dt.isoformat())
# 2012-08-28T00:45:17+00:00

Note that if you don't supply a time zone, the resulting datetime object will be naive, i.e. does not "know" of a time zone. Python will treat it as local time by default (your machine's OS setting).

To convert to US/Pacific time, you can use zoneinfo from Python 3.9's standard lib:

from zoneinfo import ZoneInfo

dt_pacific = dt.astimezone(ZoneInfo('US/Pacific'))
print(dt_pacific.isoformat())
# 2012-08-27T17:45:17-07:00

or use dateutil with older versions of Python:

from dateutil.tz import gettz # pip install python-dateutil

dt_pacific = dt.astimezone(gettz('US/Pacific'))
print(dt_pacific.isoformat())
# 2012-08-27T17:45:17-07:00

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...