python - Python 中的 Swatch 互联网时间

标签 python timezone

我有这个代码:

from time import localtime, timezone


def itime():
    """Calculate and return Swatch Internet Time

    :returns: No. of beats (Swatch Internet Time)
    :rtype: float
    """

    h, m, s = localtime()[3:6]
    beats = ((h * 3600) + (m * 60) + s + timezone) / 86.4

    if beats > 1000:
        beats -= 1000
    elif beats < 0:
        beats += 1000

    return beats

但它没有考虑时区。

如何选择时区以选择苏黎世作为时区?

服务器位于美国,但互联网时间基于瑞士

最佳答案

Swatch Internet Time 中没有时区;相反,使用新的比尔标准时间 (BMT),基于 Swatch 位于瑞士比尔的总部,相当于中欧时间、西非时间和 UTC+01。引用https://en.wikipedia.org/wiki/Swatch_Internet_Time

但是您可以通过以下步骤实现此目的:

1) - 获取当前 UTC 时间。 (现在您无需担心服务器位置及其时间)

2) - 将该时间转换为苏黎世时间,(苏黎世时间为 UTC+2)。

3) - 将苏黎世时间转换为datetime.timetuple()

以前,datetime.localtime 返回的是本地时间的 timetuple 对象。

from datetime import datetime
from dateutil import tz

def itime():
    """Calculate and return Swatch Internet Time

    :returns: No. of beats (Swatch Internet Time)
    :rtype: float
    """
    from_zone = tz.gettz('UTC')
    to_zone = tz.gettz('Europe/Zurich')
    time = datetime.utcnow()
    utc_time = time.replace(tzinfo=from_zone)
    zurich_time = utc_time.astimezone(to_zone)

    h, m, s = zurich_time.timetuple()[3:6]

    beats = ((h * 3600) + (m * 60) + s) / 86.4

    if beats > 1000:
        beats -= 1000
    elif beats < 0:
        beats += 1000

    return beats

print itime()

希望这有帮助:)

关于python - Python 中的 Swatch 互联网时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51721018/

相关文章:

python - 在从 __init__ 调用的函数中声明变量是否仍然使用 key 共享字典?

javascript - 使用 JSON 文件初始化 timezoneJS

java - 通过浏览器偏移量转换时间

go - 通过设置 Local 在 go 中全局设置时区

python - 我可以将现有的斧头对象转换为 3D 投影吗?

python - 2个隐藏层神经网络的维度不相关

python - PEP 8 和延迟导入

python - scikit-learn 使用什么距离函数来处理分类特征?

javascript - toISOstring 在 JavaScript 中不起作用

python - Django 时区 : feeling a bit confused