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

I am using Heroku to run some python code.

The code that i have written uses a predefined time like example: 16:00 and compares that with the current time and the calculates the difference like this:

now = datetime.datetime.now()

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

dif = now - starttime

Running this locally ofc uses the time in my system i guess and everything is correct. However when i post it on the server and run it there the time is one hour back. So how can i fix this so it always uses the timezone that i am in?

I live in Sweden

Thank you all, Code examples would be deeply appreciated.

EDIT1

Rest of the code looks like this:

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"

and using the imports that you provided i get this error now:

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

i tried to do like this but it did not help:

from datetime import datetime, time, timedelta

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

Find your timezone in the tz database e.g., using tzlocal module. Run on your local machine:

#!/usr/bin/env python

import tzlocal # $ pip install tzlocal

print(tzlocal.get_localzone().zone)

If tzlocal has been capable to get the timezone id then you should see something like: Europe/Paris. Pass this string to the server.

On the server:

#!/usr/bin/env python

from datetime import datetime, time

import pytz # $ pip install pytz

tz = pytz.timezone('Europe/Paris') #

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值