Search code examples
timepython-3.7delta

Time Delta problem in Hackerrank not taking good answer / Python 3


The hackerrank challenge is in the following url: https://www.hackerrank.com/challenges/python-time-delta/problem

I got testcase 0 correct, but the website is saying that I have wrong answers for testcase 1 and 2, but in my pycharm, I copied the website expected output and compared with my output and they were exactly the same.

Please have a look at my code.

#!/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)


Solution

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

    For a time zone like +0715, you correctly add “7 hours of seconds” and “15 minutes of seconds”

    For a timezone like -0715, you are adding “-7 hours of seconds” and “+15 minutes of seconds”, resulting in -6h45m, instead of -7h15m.

    You need to either use the same “sign” for both parts, or apply the sign afterwards.