gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:01:20 29 4
gpt4 key购买 nike

菜鸟在这里,

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

谢谢。

最佳答案

您可以使用 strftime("%I:%M %p")以“AM”或“PM”结尾获得标准的 12 小时格式。见 Python documentation更多详情 datetime字符串格式化。

此外,虽然它不受 native 支持,但您可以简单地使用两个 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)

关于datetime - Python转换军用时间用户输入并计算工作时间(datetime.timedelta),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16127839/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com