【问题标题】:Programmatically get the time at clock-change [closed]以编程方式获取时钟变化的时间[关闭]
【发布时间】:2014-05-27 13:33:00
【问题描述】:

我对时区和国家在时间变化时感到困惑。加利福尼亚州在上午 10 点更改时间,纽约在上午 7 点更改时间。

我如何以编程方式获取加利福尼亚州下一次时间变化的信息?

【问题讨论】:

  • 请阅读timezone tag wikidst tag wiki。如果您有特定的编程问题,请提供更多详细信息,例如您使用的编程语言、您尝试实现的目标以及到目前为止您尝试过的内容。
  • 我忘了设置编程语言。 dst 对我来说是新的。

标签: java datetime timezone dst


【解决方案1】:

要找出 DST 转换,您可以访问 Olson timezone database,例如,在 Python 中找出下一个 DST 转换的时间:

#!/usr/bin/env python
from bisect import bisect
from datetime import datetime
import pytz # $ pip install pytz

def next_dst(tz):    
    dst_transitions = getattr(tz, '_utc_transition_times', [])
    index = bisect(dst_transitions, datetime.utcnow())
    if 0 <= index < len(dst_transitions):
        return dst_transitions[index].replace(tzinfo=pytz.utc).astimezone(tz)

例如,在洛杉矶:

dt = next_dst(pytz.timezone('America/Los_Angeles'))
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

输出:

2014-11-02 01:00:00 PST-0800

或在当地时区:

from tzlocal import get_localzone # $ pip install tzlocal

dt = next_dst(get_localzone())
if dt is not None:
   print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
else:
   print("no future DST transitions")

【讨论】:

  • 太好了,效果很好。
猜你喜欢
  • 2016-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-19
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
相关资源
最近更新 更多