将12小时时钟时间转换为24小时时钟时间

2024-10-19 14:27:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道在S/O网络上有很多答案,但我在HackerRank python 3 shell中遇到了一个不寻常的错误,下面的代码在Jupyter notebook中运行良好

time1=input()
l=time1.split(':')
if 'PM' in l[2]:
    l[0]=int(l[0])+12
    l[2]=l[2].rstrip('PM')
elif 'AM' in l[2]:
    l[2]=l[2].rstrip('AM')
    if l[0]=='12':
        l[0]="0"
time2=''
for i in range(2):
    time2+=str(l[i])+':'
time2+=l[2]
print(time2)

这是challenge

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Note:

  • 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.
  • 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.

Example

  • s = '12:01:00PM'

    Return '12:01:00'.

  • s = '12:01:00AM'

    Return '00:01:00'.

Function Description

Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.

timeConversion has the following parameter(s):

  • string s: a time in 12 hour format

Returns

  • string: the time in 12 hour format

Input Format

A single string s that represents a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM).

Constraints

  • All input times are valid

Sample Input 0

07:05:45PM

Sample Output 0

19:05:45

我确实试过运行同样的案例,在H/R上出现错误,但在J/p笔记本上工作正常

另外,我知道这可能是我提出的一个超级基本的问题,但请原谅,我还是个新手:)


Tags: theinformatinputstringiftimeon
2条回答

似乎有两个问题:

  • 当输入时间为12:00:00PM时,代码返回无效结果(24:00:00)。在这种情况下,它应该保持12个不变
  • 当输入为12:00:00AM时,代码返回的小时数只有1位,而2位是必需的

因此,改变这一点:

l[0] = int(l[0]) + 12

致:

if l[0] != "12":
    l[0] = int(l[0]) + 12

改变这一点:

l[0] = "0"

致:

l[0] = "00"

有了这一点,它就会起作用。请注意,要求您编写timeConversion函数的主体,因此您的代码中不应该有硬编码的time1=

最终的代码可能是这样的:

def timeConversion(time1):
    h = time1[0:2]
    if time1[-2:] == "PM'":
        if h != "12":
            h = str(int(h) + 12)
    elif h == '12':
        h = "00"
    return h + time1[2:-2]
def conv24(time):
    """
    Converts 12HR clock to 24HR clock
    time should be either 
    'hh:mm:ssAM' or 'hh:mm:ssPM'
    """

    l = time.split(':')
    if 'PM' in l[2]:
        v = int(l[0])
        if v < 12 and v > 0:
            v += 12
            l[0] = str(v)
        l[2] = l[2].strip('PM')
    elif 'AM' in l[2]:
        v = int(l[0])
        if v == 12:
            l[0] = '00'
        l[2] = l[2].strip('AM')
    res = ''
    for i in l:
        res += i + ":"
    return res.rstrip(':')

相关问题 更多 >