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
351 views
in Technique[技术] by (71.8m points)

python - From a timezone and a UTC time, get the difference in seconds vs local time at that point in time

This should be very simple, but I can't quite figure it out in Python. I want to have a function which takes two arguments, a UTC time in seconds and a zoneinfo name like 'Europe/Vienna' and returns the offset in seconds from local time and UTC for that point in time.

In C it would be:

/* ... code to to set local time to the time zone I want to compare against,
   not shown here. Then call function below to get difference vs localtime.
   Hardly an ideal solution,
   but just to demonstrate what I want in a "lingua franca" (C): */


int get_diff_vs_localtime(const time_t original_utc_time)
{
    struct tm* ts;

    ts = localtime(&original_utc_time);

    return mktime(ts) - original_utc_time;
}

I guess my question really boils down to: "given an Olson timezone (example 'Europe/Stockholm') and a UTC time, what is the local time?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Assuming "UTC time in seconds" means POSIX timestamp. To convert it to Stockholm time:

from datetime import datetime
import pytz

tz = pytz.timezone('Europe/Stockholm')

utc_dt = datetime.utcfromtimestamp(posix_timestamp).replace(tzinfo=pytz.utc)
dt = tz.normalize(utc_dt.astimezone(tz))
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

tz.normalize() is unnecessary if the source timezone is UTC (like in this case).

A simpler alternative is to use fromtimestamp()'s tz parameter, to convert "seconds since the epoch" to local time:

from datetime import datetime
import pytz

tz = pytz.timezone('Europe/Stockholm')

dt = datetime.fromtimestamp(posix_timestamp, tz)
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

Both examples produce the same result.

If local machine uses "right" timezones then to convert POSIX timestamp received from an external source to UTC, an explicit formula could be used:

from datetime import datetime, timedelta
import pytz

utc_dt = datetime(1970, 1, 1, tzinfo=pytz.utc) + timedelta(seconds=posix_timestamp)

The latest formula may also support a larger date range (less likely issues with dates before 1970, after 2038 or 3000 years).

If the timestamp comes from the local "right" source then the first two examples should be used instead (they call "right" time.gmtime()).


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

...