python - python 中的 datetime.now 在本地和服务器上运行时不同

标签 python heroku timezone pytz

我正在使用 Heroku 运行一些 python 代码。

我编写的代码使用预定义时间,例如:16:00,并将其与当前时间进行比较,并计算差异,如下所示:

now = datetime.datetime.now()
starttime = datetime.datetime.combine(datetime.date.today(), datetime.time(int(hour), int(minute)))
dif = now - starttime

在本地运行这个 ofc 使用我系统中的时间,我猜一切都是正确的。但是,当我将其发布到服务器上并在那里运行时,时间倒退了一小时。那么我该如何解决这个问题,以便它始终使用我所在的时区?

我住在瑞典

谢谢大家,代码示例将不胜感激。

编辑1

其余代码如下所示:

if dif < datetime.timedelta(seconds=0):
    hmm = 3                                     
elif dif < datetime.timedelta(seconds=45*60):
    t = dif.total_seconds() / 60
    time, trash = str(t).split(".")
    time = time+"'"
elif dif < datetime.timedelta(seconds=48*60):
    time = "45'"
elif dif < datetime.timedelta(seconds=58*60):
    time = "HT"
elif dif < datetime.timedelta(seconds=103*60):
    t = (dif.total_seconds() - 840) / 60
    time, trash = str(t).split(".")
    time = time+"'"
elif dif < datetime.timedelta(seconds=108*60):
    time = "90'"
else:
    time = "FT"

并使用您提供的导入,我现在收到此错误:

AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'

我尝试这样做,但没有帮助:

from datetime import datetime, time, timedelta

最佳答案

So how can i fix this so it always uses the timezone that i am in?

在 tz 数据库中查找您的时区,例如使用 tzlocal module 。在本地计算机上运行:

#!/usr/bin/env python
import tzlocal # $ pip install tzlocal

print(tzlocal.get_localzone().zone)

如果tzlocal能够获取时区ID,那么您应该看到类似:Europe/Paris。将此字符串传递给服务器。

在服务器上:

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

tz = pytz.timezone('Europe/Paris') # <- put your local timezone here
now = datetime.now(tz) # the current time in your local timezone
naive_starttime = datetime.combine(now, time(int(hour), int(minute)))
starttime = tz.localize(naive_starttime, is_dst=None) # make it aware
dif = now - starttime

关于python - python 中的 datetime.now 在本地和服务器上运行时不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28775650/

相关文章:

python, mongoengine - 喜欢/正则表达式搜索

Heroku 上的 Python-Tornado

ruby-on-rails - Heroku Migrate 数据库更改

python - 将原始日期时间对象转换为 UTC 时区

mysql - Django 在将其保存到数据库时是否会破坏时区感知 DateTimeField?

python - 如何在谷歌云上安装 ortools 库

python - 从不同来源的跨平台音频导入

python - 随机播放 DataFrame 行

ruby-on-rails - bundle 安装和访问被拒绝错误的问题

ruby-on-rails - 在Ruby on Rails中使用12小时时间和时区的time_select