HackerRank Time Delta problem solution in python

In this HackerRank Time Delta problem solution in python, When users post an update on social media,such as a URL, image, status update etc., other users in their network are able to view this new post on their news feed. Users can also see exactly when the post was published, i.e, how many hours, minutes or seconds ago.

Since sometimes posts are published and viewed in different time zones, this can be confusing. You are given two timestamps of one such post that a user can see on his newsfeed in the following format:

Day dd Mon yyyy hh:mm:ss +xxxx

Here +xxxx represents the time zone. Your task is to print the absolute difference (in seconds) between them.

HackerRank Time Delta solution in python


Problem solution in Python 2 programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
from datetime import datetime, timedelta

def gettime():
    s = raw_input()
    t = datetime.strptime(s[:-6], "%a %d %b %Y %H:%M:%S")
    m = int(s[-2:])  
    h = int(s[-4:-2])
    if s[-5] == '+':
        t -= timedelta(hours=h, minutes=m)
    else:
        t += timedelta(hours=h, minutes=m)
    return t
for _ in xrange(input()):
    t1 = gettime()
    t2 = gettime()
    d = abs(t1 - t2)
    #print d
    print d.days * 86400 + d.seconds


Problem solution in Python 3 programming.

import datetime

format_string = "%a %d %b %Y %H:%M:%S %z"
T = int(input())

for test in range(T):
    t1 = str(input())
    t2 = str(input())

    parsed_t1 = datetime.datetime.strptime(t1, format_string)
    parsed_t2 = datetime.datetime.strptime(t2, format_string)

    diff = parsed_t2 - parsed_t1

    print (int(abs(diff.total_seconds())))


Problem solution in pypy programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
from datetime import datetime,timedelta
def timeformatter(t):
    ret = datetime.strptime(t[:-6],"%a %d %b %Y %H:%M:%S")
    if t[-5] == '-':
        ret +=  timedelta(hours=int(t[-4:-2]),minutes=int(t[-2:]))
    else :
        ret -=  timedelta(hours=int(t[-4:-2]),minutes=int(t[-2:]))
    return ret
T = int(raw_input())

for i in range(T):
    t1,t2= [timeformatter(raw_input()) for _ in range(2)]
    print abs(int((t1-t2).total_seconds()))


Problem solution in pypy3 programming.

from datetime import datetime
date_strftime =  '%a %d %b %Y %H:%M:%S %z'
a = []
count = input()
for i in range(int(count)):
    start = input()
    end = input()
    a.append(abs(
        datetime.strptime(end, date_strftime) -
        datetime.strptime(start, date_strftime)).total_seconds())
for i in range(int(count)):
    print (int(a[i]))


Post a Comment

0 Comments