问题描述
这应该很简单,但我在 Python 中无法完全弄清楚.我想要一个函数,它需要两个参数,一个以秒为单位的 UTC 时间和一个 zoneinfo name 之类的'Europe/Vienna' 并返回与本地时间和 UTC 时间的秒数的偏移量.
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.
在 C 中应该是:
/* ... 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;
}
我想我的问题真的可以归结为:鉴于 Olson 时区(例如 'Europe/Stockholm') 和 UTC 时间,当地时间是多少?
I guess my question really boils down to: "given an Olson timezone (example 'Europe/Stockholm') and a UTC time, what is the local time?
推荐答案
假设UTC 时间以秒为单位"表示 POSIX 时间戳.将其转换为斯德哥尔摩时间:
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()
如果源时区是 UTC(如本例),则不需要.
tz.normalize()
is unnecessary if the source timezone is UTC (like in this case).
更简单的替代方法是使用 fromtimestamp()
的 tz
参数,将自纪元以来的秒数"转换为本地时间:
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.
如果本地机器使用正确"的时区,然后将从外部源接收到的 POSIX 时间戳转换为 UTC,则可以使用明确的公式:
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)
最新公式还可能支持更大的日期范围(1970 年之前、2038 年或 3000 年之后的日期不太可能出现问题).
The latest formula may also support a larger date range (less likely issues with dates before 1970, after 2038 or 3000 years).
如果时间戳来自本地正确"源,则应使用前两个示例(它们称为正确"time.gmtime()
).
If the timestamp comes from the local "right" source then the first two examples should be used instead (they call "right" time.gmtime()
).
这篇关于从时区和 UTC 时间,获取该时间点与本地时间的秒差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!