首页 > 解决方案 > Hackerrank 中的时间增量问题没有得到很好的答案/Python 3

问题描述

hackerrank 挑战位于以下网址:https ://www.hackerrank.com/challenges/python-time-delta/problem

我得到了测试用例 0 正确,但是网站说我对测试用例 1 和 2 的答案有误,但是在我的 pycharm 中,我复制了网站的预期输出并与我的输出进行比较,它们完全相同。

请看一下我的代码。

#!/bin/pyth
# Complete the time_delta function below.
from datetime import datetime
def time_delta(tmp1, tmp2):
    dicto = {'Jan':1, 'Feb':2, 'Mar':3,
         'Apr':4, 'May':5, 'Jun':6,
         'Jul':7, 'Aug':8, 'Sep':9,
         'Oct':10, 'Nov':11, 'Dec':12}

    # extracting t1 from first timestamp without -xxxx
    t1 = datetime(int(tmp1[2]), dicto[tmp1[1]], int(tmp1[0]), int(tmp1[3][:2]),int(tmp1[3][3:5]), int(tmp1[3][6:])) 

    # extracting t1 from second timestamp without -xxxx
    t2 = datetime(int(tmp2[2]), dicto[tmp2[1]], int(tmp2[0]), int(tmp2[3][:2]), int(tmp2[3][3:5]), int(tmp2[3][6:])) 

    # converting -xxxx of timestamp 1
    t1_utc = int(tmp1[4][:3])*3600 + int(tmp1[4][3:])*60 

    # converting -xxxx of timestamp 2
    t2_utc = int(tmp2[4][:3])*3600 + int(tmp2[4][3:])*60 

    # absolute difference
    return abs(int((t1-t2).total_seconds()-(t1_utc-t2_utc))) 

if __name__ == '__main__':
    # fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input())

    for t_itr in range(t):
        tmp1 = list(input().split(' '))[1:]
        tmp2 = list(input().split(' '))[1:]
        delta = time_delta(tmp1, tmp2)
        print(delta)

标签: timepython-3.7delta

解决方案


t1_utc = int(tmp1[4][:3])*3600 + int(tmp1[4][3:])*60

对于像这样的时区+0715,您正确添加了“7 小时秒”和“15 分钟秒”</p>

对于像这样的时区-0715,您添加“-7 小时秒”和“+15 分钟秒”,结果是 -6h45m,而不是 -7h15m。

您需要对两个部分使用相同的“标志”,或者在之后应用该标志。


推荐阅读