2

菜鸟在这里,

我一直试图将军事时间的用户输入呈现为标准时间。该代码到目前为止有效,但我需要从结束时间减去 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.

谢谢。

4

2 回答 2

3

您可以使用strftime("%I:%M %p")以“AM”或“PM”结尾的标准 12 小时格式。有关字符串格式的更多详细信息,请参阅Python 文档。datetime

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

下面的代码就足够了,尽管一定要使用正确的错误检查。;)
--ap

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)
于 2013-04-21T04:43:25.103 回答
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')
于 2017-08-23T05:56:20.413 回答