Python转换军事时间用户输入并计算工作时间(datetime.timedelta)

时间:2013-04-21 04:00:30

标签: datetime time python-2.7

Noob,

我一直试图在军事时间内将用户输入提供给标准时间。代码到目前为止工作,但我需要从结束时间减去12小时,以标准时间显示。如何使用datetime.time执行此操作?另外,我是否需要将原始用户输入转换为整数以执行datetime.timedelta计算?以前的问题似乎没有回答我的编码问题。

我的代码是:

def timeconvert():
    print "Hello and welcome to Python Payroll 1.0."
    print ""
    # User input for start time. Variable stored. 
    start = raw_input("Enter your check-in time in military format (0900): ") 
    # User input for end time. Variable stored.
    end = raw_input("Enter your check-out time in military format (1700): ") 
    print ""

    # ---------------------------------------------------------------------------
    # Present user input in standard time format hhmm = hh:mm
    # ---------------------------------------------------------------------------
    import datetime, time
    convert_start = datetime.time(hour=int(start[0:2]), minute=int(start[2:4]))
    # need to find a way to subtract 12 from the hour to present end time in standard time
    convert_end = datetime.time(hour=int(end[0:2]), minute=int(end[2:4]))
    print 'You started at', convert_start.strftime("%H:%M"),'am', 'and ended at', convert_end.strftime("%H:%M"), 'pm' 

    # ---------------------------------------------------------------------------
    # Use timedelta to caculate time worked.
    # ---------------------------------------------------------------------------
    # print datetime.timedelta
timeconvert()
raw_input("Press ENTER to exit program") # Closes program.

感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用strftime("%I:%M %p")来获得标准的12小时格式,最后使用“AM”或“PM”。有关datetime字符串格式的详细信息,请参阅Python documentation

此外,虽然它本身不受支持,但您只需使用两个datetime.time实例作为timedelata构造函数的一部分进行计算。

下面的代码应该足够了,但绝对应该使用正确的错误检查。 ;)
留学美国相关考试

start = raw_input("Enter your check-in time in military format (0900): ") 
end = raw_input("Enter your check-out time in military format (1700): ") 

# convert user input to datetime instances
start_t = datetime.time(hour=int(start[0:2]), minute=int(start[2:4]))
end_t = datetime.time(hour=int(end[0:2]), minute=int(end[2:4]))
delta_t = datetime.timedelta(
    hours = (end_t.hour - start_t.hour),
    minutes = (end_t.minute - start_t.minute)
    )

# datetime format
fmt = "%I:%M %p"
print 'You started at %s and ended at %s' % (start_t.strftime(fmt), end_t.strftime(fmt))
print 'You worked for %s' % (delta_t)

答案 1 :(得分:0)

def time12hr(string):
    hours  =  string[:2] 
    minutes = string[2:]
    x = " "
    if int(hours) == 12:
       x = "p.m."
       hours = "12"
    elif int(hours) == 00:
         x = "a.m."
         hours = "12" 
    elif int(hours) > 12:
       x = "p.m."
       hours  = str(int(hours) - 12)
    else:
        x = "a.m."
    return "%s:%s %s"%(hours ,minutes,x)
print time12hr('1202')
print time12hr('1200')
print time12hr('0059')
print time12hr('1301')
print time12hr('0000')