【问题标题】:Python - how to run function at a certain PST/PDT time?Python - 如何在某个 PST/PDT 时间运行函数?
【发布时间】:2018-07-13 08:54:11
【问题描述】:

我开始学习 python,我尝试创建一个脚本来在某个时间运行某个命令。这是我目前所拥有的:

import datetime

day_of_week = datetime.date.today().weekday() # 0 is Monday, 6 is Sunday
time = datetime.datetime.now().time()

if day_of_week == 4 and (time >= datetime.time(2,45) and time < datetime.time(9)):
    #do something
elif (day_of_week == 3 and time > datetime.time(22)) or (day_of_week == 4 and time < datetime.time(2,45)):
    #wait until 2h45
else:
    #do nothing

我希望脚本仅在某一天以及大约 19h00 PST/PDT(2h45 GMT/UTC)时继续运行。我写的那个适用于 GMT/UTC,但我确信当夏令时开始或我将本地时区更改为其他时区时它会失败。

如何让脚本检查 PST/PDT 中的当前时间并从那里继续,忽略或转换本地时区?

【问题讨论】:

  • 您为什么要尝试在 Python 中执行此操作,而不是使用操作系统内置的功能(*nix 上的 cron,Windows 上的任务计划程序),这两者都会为您完成 DST 调整工作?
  • 我不想按计划运行它。我想在需要时打开脚本。我要把这个发给朋友,一天的限制是避免在不应该运行的时候运行脚本。

标签: python python-3.x timezone


【解决方案1】:

@Ruben,请试试下面的代码。它总是查看美国/太平洋时区的时间。希望能帮助到你。谢谢。

import datetime
import pytz

pst_timezone = pytz.timezone("US/Pacific")
time=datetime.datetime.now(pst_timezone).time()
print(time)

Result: 12:13:10.136603

【讨论】:

  • 完美运行。我之前实际上已经尝试过使用 pytz ,但我无法让它以某种方式工作。谢谢。
【解决方案2】:

Pythons Datetime 从系统时间中提取。因此,如果系统设置为使用 DST,那么您会没事的。

如果您不相信或不能相信系统时间,那么没有任何内置函数是准确的。然后,您需要让您的程序退出并从另一台服务器提取时间。

【讨论】:

    【解决方案3】:

    你应该看看pytz

    Python: display the time in a different time zone 也会有所帮助

    【讨论】:

      猜你喜欢
      • 2015-09-08
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 2019-05-23
      • 2014-05-20
      • 1970-01-01
      相关资源
      最近更新 更多