2014-12-25 1 views
0

변수를 자정까지 시간을 설정할 수 있는지 알고 싶습니다.두 번 차이 (파이썬)

#!/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 
+0

어,이 부분이 작동하지 않습니까? –

+0

자정은 튜플이지만 문자열이어야합니다. –

+0

그래서 1900 년에 토요일에 서명합니다. 그날 밤 0202에서 서명하십시오. 이 오류가 발생합니다 : diff = (datetime.strptime (signOffSun1, FMT) - datetime.strptime (자정, FMT)) 형식 오류 : 나는이 같은 문자열을 할 때하지 –

답변

0

당신은 당신이 원하는 것을 너무 정확하게 확실하지 signOnSun1를 사용하는 표시되지 않습니다 :

내가 지금까지 내가이 가지고 raw_input을 자정 고정되는 값

로 떨어져 서명합니다 하지만 당신이 원하는이 가까이 있어야한다 :

from datetime import datetime 
#Variablesr 
FMT = '%H:%M' #Time Format use HH:MM 
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 = "00:00" # make midnight a string 

amp = 2.40 #Morning shift penalties 
pmp = 2.50 #Afternoon shift penalties 
ns = 4.4 #Night shift penalties 
cabAll = 8.34 #Cab Allowance 
# make sure user know format to use 
signOnSun1 = raw_input("What time did you sign on Sunday, enter in format HH:MM: ") 
signOffSun1 = raw_input("What time did you sign off Sunday, enter in format HH:MM: ") 
# use Midnight string and FMT 
diff = (datetime.strptime(signOffSun1, FMT) - datetime.strptime(Midnight,FMT)) 
print diff 

을 정말 당신이 사용자가 try/except 블록을 사용하여 정확한 데이터를 입력 확인해야하고 c를하면 당신이 잡힐 것

FMT = '%H:%M-%Y-%m-%d' #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 = "00:00-1900-01-02" 

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, enter in format HH:MM: ") 
signOffSun1 = raw_input("What time did you sign off Sunday, enter in format HH:MM: ") 
diff = datetime.strptime(Midnight, FMT) - datetime.strptime("{}-1900-01-01".format(signOnSun1), FMT) 
print diff 
+0

절대 천재. 내가 빠진 것은 모두 "0000"이었습니다 ... 지금은 바보가 느껴집니다. –

+0

걱정하지 마시고, try/except와 while 루프를 사용하여 좋은 생각이 될 것입니다. –

0

당신은 사람들이 당신이해야 작업 시간 수를 처리하는 경우 : 모든 시간은 자정까지 당신이 후 어느 날 자정을 설정 날짜를 하드 코딩 할 경우 전에 자정

후 시간을 omparing DST 전환 (다른 이유로 UTC 오프셋의 변경)을 고려하지 않으면 결과가 잘못 될 수 있습니다 (일반적으로 1 시간 씩).

정확하게 자정을 찾는 것은 쉽지 않습니다. How do I get the UTC time of “midnight” for a given timezone?

정확한 결과를 얻으려면 예를 들어 마지막 일요일로 가정하여 시간 외에 날짜를 지정해야합니다. 그리고 당신은 현지 시간대를 알아야하고 (이식성을 위해서) 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) 
     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) 

을 번 다음 같은 현지 시간 두 번 발생할 수 있습니다 ("후퇴") DST 전환 중입니다. 그런 다음 (날짜 외에도) 여름 시간인지 ('사인온', '사인 오프')인지, 시간을 모호하지 않게 알 필요가 있습니다.

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) 
: 로컬 시간대를 처리 할 필요가 없습니다 당신은 UTC 시간을 요청할 수 있습니다 경우

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.") 

모든 것이 훨씬 간단합니다 : yes_or_no() 작은 유틸리티 함수입니다

가능한 경우 현지 시간 대신 UTC 시간으로 작업하는 것이 좋습니다 (사람들에게 UTC로 시간을 제공하도록 요청할 수있는 경우). 당신이 tzlocal 모듈을 설치할 수 없습니다 다음 로컬 시간을 명확하게하기 위해 time.mktime()를 사용할 수 있습니다 UTC 시간을 사용할 수없는 경우, 참조


는 (그것은 TZ 데이터베이스를 사용하여 위의 방법보다 신뢰할 수 있습니다) my answer to "Find if 24 hrs have passed between datetimes - Python".