两次之间的差异(python) [英] Difference Between Two Times (python)

查看:157
本文介绍了两次之间的差异(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想知道我是否可以将变量设置为午餐的时间。

我想要签署一个raw_input和午夜来固定值



到目前为止,我有这个:

 #!/ usr / bin / python 
from datetime import datetime
from Tkinter import *
import math
#Variablesr
FMT ='%H%M'#Time格式
rate1 = 35.34 #Base小时
rate2 = 35.34 #Base小时价格
rate3 = 35.34 #Base小时价
rate4 = 35.34 #Base小时价
rate5 = 35.34 #Base小时价
rate6 = 50 #Base小时价格
rate7 = 70 #Base小时价格

午夜= 0000,FMT
amp = 2.40#移动罚款
pmp = 2.50#下午班罚款
ns = 4.4#夜班罚款
cabAll = 8.34 #Cab津贴

signOnSun1 = raw_input(你星期几几点什么时候 );
signOffSun1 = raw_input(星期日你星期天离开什么时间);

diff =(datetime.strptime(signOffSun1,FMT) - datetime.strptime(Midnight,FMT))
print diff


解决方案

如果您正在处理人员工作的小时数,那么您应该进行DST转换(由于其他原因,UTC偏移量的更改),否则结果可能是错误的(通常一个小时)。



正确找到午夜并不重要。请参阅如何获取给定时区的午夜的UTC时间?



要获得正确的结果,您应该指定一个日期,除了时间之外,例如,假设最后一个星期天。您需要知道当地时区和(便携性),您需要一个历史时区数据库,例如由 pytz 模块提供。 tzlocal 模块可以找到您当地的时区:

  from datetime import datetime, timedelta 
from tzlocal import get_localzone#$ pip install tzlocal
from pytz import AmbiguousTimeError

DAY = timedelta(1)
local_timezone = get_localzone()#get pytz timezone
time_format =%H:%M

def asktime(prompt,format):
while True:
try:
return datetime.strptime raw_input(prompt),format)
除了ValueError:
print('无效的时间格式,预期的%s。再试一次'%format)

def disambiguate(time,date )
d = datetime.combine(日期,时间).replace(tzinfo =无)
try:
返回local_timezone.localize(d,is_dst =无)
除了AmbiguousTimeError:
is_dst = yes_or_no('夏天时间(%s)'%d)
返回local_timezone.localize(d,is_dst = is_dst)
#允许NonExistentTimeError传播ate

#find last Sunday
sunday = datetime.now(local_timezone)
while sunday.weekday()!= 6:#Sunday is 6
sunday - = DAY

#获取'sign on','sign off'times
#注意:假设没有24h + shift
signon = asktime(你几星期天在什么时候登录? ,time_format)
signoff = asktime(星期日你星期日离开什么时间,time_format)
如果signoff<登录:#signon是前一天(星期六)
signon = disambiguate(signon,sunday.date() - DAY)
signoff = disambiguate(signoff,sunday)
print(Signon time %s%登录)
打印(签出时间%s%签名)
diff = signoff - 登录
print(差异%s%diff)

如果登录,注销时间是在DST转换期间(退回),则本地时间相同可能会发生两次。然后(除了一个日期),你需要知道是否在(登录,注销)的夏季时间,以使时间无歧视。



其中 yes_or_no()是一个小的实用功能:

  def yes_or_no(prompt):
while True:
answer = raw_input(prompt)
if {'yes','no'}中的answer.lower():
return answer = ='yes'
print(请,回答是或否,再试一次。)






如果您不需要处理本地时区,您可以要求UTC时间更简单:

  signon = asktime(星期日你在什么UTC时间,time_format)
signoff = asktime(星期天你星期几什么UTC时间:,time_format)
#支持24h +转移
而签到<登录:#signon在上一个日期
signon - = DAY
diff = signoff - signon
print(diff)

这就是为什么建议使用UTC时间而不是当地时间(如果可以要求人们提供UTC的时间)。






如果您无法安装 tzlocal 模块,则无法使用UTC时间您可以使用 time.mktime()来消除当地时间的歧义(可能比使用tz数据库的上述方法更不可靠),请参阅我的答案为查找是否24小时在datetimes之间 - Python


Just want to know if i can set the variable a sign off time to midnight.

i want sign off to be a raw_input and midnight to be fixed value

so far i have this:

#!/usr/bin/python
from datetime import datetime
from Tkinter import *
import math
#Variablesr
FMT = '%H%M' #Time Format
rate1 = 35.34 #Base Hourly Rate
rate2 = 35.34 #Base Hourly Rate
rate3 = 35.34 #Base Hourly Rate
rate4 = 35.34 #Base Hourly Rate
rate5 = 35.34 #Base Hourly Rate
rate6 = 50 #Base Hourly Rate
rate7 = 70 #Base Hourly Rate

Midnight = 0000,FMT
amp = 2.40 #Morning shift penalties
pmp = 2.50 #Afternoon shift penalties
ns = 4.4 #Night shift penalties
cabAll = 8.34 #Cab Allowance

signOnSun1 = raw_input("What time did you sign on Sunday: ");
signOffSun1 = raw_input("What time did you sign off Sunday: ");

diff = (datetime.strptime(signOffSun1, FMT) - datetime.strptime (Midnight, FMT))
print diff

解决方案

If you are dealing with number of hours people work then you should take DST transitions (and the changes in UTC offset for other reasons) into account otherwise the result can be wrong (by an hour usually).

It is not trivial to find midnight correctly. See How do I get the UTC time of "midnight" for a given timezone?

To get correct results, you should specify a date in addition to the time e.g., assume the last Sunday. And you need to know the local timezone and (for portability) you need a historical timezone database such as provided by pytz module. tzlocal module can find your local timezone:

from datetime import datetime, timedelta
from tzlocal import get_localzone # $ pip install tzlocal
from pytz import AmbiguousTimeError

DAY = timedelta(1)
local_timezone = get_localzone() # get pytz timezone
time_format = "%H:%M"

def asktime(prompt, format):
    while True:
        try:
            return datetime.strptime(raw_input(prompt), format)
        except ValueError:
            print('Invalid time format, expected %s. Try again.' % format)

def disambiguate(time, date):
    d = datetime.combine(date, time).replace(tzinfo=None)
    try:
        return local_timezone.localize(d, is_dst=None)
    except AmbiguousTimeError:
        is_dst = yes_or_no('Was it summer time (%s)?' % d)
        return local_timezone.localize(d, is_dst=is_dst)
    # allow NonExistentTimeError to propagate

# find last Sunday
sunday = datetime.now(local_timezone)
while sunday.weekday() != 6: # Sunday is 6
    sunday -= DAY

# get 'sign on', 'sign off' times
#NOTE: assume, no 24h+ shifts
signon = asktime("What time did you sign on Sunday: ", time_format)
signoff = asktime("What time did you sign off Sunday: ", time_format)
if signoff < signon: # signon is a day before (Saturday)
   signon = disambiguate(signon, sunday.date() - DAY)
signoff = disambiguate(signoff, sunday)
print("Signon time %s" % signon)
print("Signoff time %s" % signoff)
diff = signoff - signon
print("The difference %s" % diff)

If 'sign on', 'sign off' times are during DST transition ("fall back") then the same local time may occur twice. Then (in addition to a date) you need to know whether it was a summer time during ('sign on', 'sign off'), to make the time unambiguous.

Where yes_or_no() is a small utility function:

def yes_or_no(prompt):
    while True:
        answer = raw_input(prompt)
        if answer.lower() in {'yes', 'no'}:
            return answer == 'yes'
        print("Please, answer 'yes' or 'no'. Try again.")


Everything is much simpler if you don't need to deal with the local timezone and you can ask for UTC time:

signon = asktime("What UTC time did you sign on Sunday: ", time_format)
signoff = asktime("What UTC time did you sign off Sunday: ", time_format)
# support 24h+ shifts
while signoff < signon: # signon is on a previous date
   signon -= DAY
diff = signoff - signon
print(diff)

And that is why it is recommended to work with UTC time instead of the local time if possible (if you can ask people to provide time in UTC).


If you can't install tzlocal module and can't use UTC time then you could use time.mktime() to disambiguate the local time (it may be less reliable than the above method that uses the tz database), see my answer to "Find if 24 hrs have passed between datetimes - Python".

这篇关于两次之间的差异(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆