在不使用任何库的情况下,我正在尝试解决 Hackerrank 问题“Time Conversion”,其问题陈述复制如下。
我想出了以下内容:
time = raw_input().strip()
meridian = time[-2:] # "AM" or "PM"
time_without_meridian = time[:-2]
hour = int(time[:2])
if meridian == "AM":
hour = (hour+1) % 12 - 1
print ("%02d" % hour) + time_without_meridian[2:]
elif meridian == "PM":
hour += 12
print str(hour) + time_without_meridian[2:]
但是,这在一个测试用例上失败了:
由于测试用例对用户隐藏,所以我很难找出问题发生的地方。 “12:00:00AM”正确转换为“00:00:00”,“01:00:00AM”正确转换为“01:00:00”(填充零)。这个实现可能有什么问题?
它比您拥有的方式还要简单。
hour = int(time[:2])
meridian = time[8:]
# Special-case '12AM' -> 0, '12PM' -> 12 (not 24)
if (hour == 12):
hour = 0
if (meridian == 'PM'):
hour += 12
print("%02d" % hour + time[2:8])
您已经解决了问题,但这里还有另一个可能的答案:
from datetime import datetime
def solution(time):
return datetime.strptime(time, '%I:%M:%S%p').strftime('%H:%M:%S')
if __name__ == '__main__':
tests = [
"12:00:00PM",
"12:00:00AM",
"07:05:45PM"
]
for t in tests:
print solution(t)
虽然它使用的是 python 库:-)
from datetime import datetime
#Note the leading zero in 05 below, which is required for the formats used below
regular_time = input("Enter a regular time in 05:48 PM format: ")
#%I is for regular time. %H is for 24 hr time, aka "military time"
#%p is for AM/PM
military_time = datetime.strptime(regtime, '%I:%M %p').strftime('%H:%M')
print(f"regular time is: {regular_time"}
print(f"militarytime is {military_time}")
以下链接被证明非常有帮助:https://strftime.org/
我发现了:它将“12:00:00PM”转换为“24:00:00”而不是“12:00:00”。我修改了代码如下:
time = raw_input().strip()
meridian = time[-2:] # "AM" or "PM"
time_without_meridian = time[:-2]
hour = int(time[:2])
if meridian == "AM":
hour = (hour+1) % 12 - 1
print ("%02d" % hour) + time_without_meridian[2:]
elif meridian == "PM":
hour = hour % 12 + 12
print str(hour) + time_without_meridian[2:]
导致它通过所有测试用例(见下文)。
dt_m = datetime.datetime.fromtimestamp(m_time)
hour_m = (dt_m.hour%12)+1 #dt_m.hour+1
offset_dt = datetime.datetime(dt_m.year, dt_m.month, dt_m.day, hour_m , dt_m.minute, dt_m.second, dt_m.microsecond)
建议学习strptime和strftime。该函数依赖于 Python 的
datetime
模块来处理时间转换。
from datetime import datetime
def timeConversion(s):
return datetime.strptime(s, "%I:%M:%S%p").strftime("%H:%M:%S")
下表解释了格式说明符
%H
、%I
、%M
、%S
和 %p
:
说明符 | 描述 |
---|---|
|
小时(24 小时制,00-23) |
|
小时(12 小时制,01-12) |
|
分钟(00-59) |
|
第二个(00-59) |
|
AM/PM 标记 |
结合使用:
对于像
07:05:45PM
这样的时间,完整的格式说明符将是 %I:%M:%S%p
。