# HackerRank Solution: Python Time Delta [3 Methods]

Written By - Bashir Alam

## Question: Python Time Delta (Date and Time)

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.

Input Format:

The first line contains T, the number of testcases.
Each testcase contains 2 lines, representing time t1 and time t2.

Constraints:

• Input contains only valid timestamps
• year <= 3000

Output Format:

Print the absolute difference(t1 - t2) in seconds.

Sample Input :

```2
Sun 10 May 2015 13:54:36 -0700
Sun 10 May 2015 13:54:36 -0000
Sat 02 May 2015 19:54:36 +0530
Fri 01 May 2015 13:54:36 -0000```

Sample Output :

```25200
88200```

Explanation :
In the first query, when we compare the time in UTC for both time stamps, we see a difference of 7 hours. which is 7*3600 seconds or 25200 seconds

Similarly, in the second query, the time difference is 5 hours and 30 minutes for the time zone adjusting for that we have a difference of 1 day and 30 minutes. Or 24*3600+30*60 => 88200.

## Possible Solutions

Now we will use various methods to solve the given question: In the HackerRank you will find the following code already written for you.

``````import math
import os
import random
import re
import sys

# Complete the time_delta function below.
def time_delta(t1, t2):

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

t = int(input())

for t_itr in range(t):
t1 = input()

t2 = input()

delta = time_delta(t1, t2)

fptr.write(delta + '\n')

fptr.close()
``````

So, we have to put our the solution in the given function: We will use the following methods to solve this problem:

1. Using `datetime` module
2. Using `dateutil` module
3. Using `split` method

### Solution-1: Using the datetime module

We already have a function `time_delta` which takes two parameters. We have to put the solution there as shown below:

``````import math
import os
import random
import re
import sys

# Complete the time_delta function below.
# importing the datetime function
from datetime import datetime
def time_delta(t1, t2):
a=datetime.strptime(t1,"%a %d %b %Y %H:%M:%S %z")
b=datetime.strptime(t2,"%a %d %b %Y %H:%M:%S %z")

return str(int(abs((a-b).total_seconds())))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

t = int(input())

for t_itr in range(t):
t1 = input()

t2 = input()

delta = time_delta(t1, t2)

fptr.write(delta + '\n')

fptr.close()
``````

The function first imports the datetime module, which provides classes for manipulating dates and times. It then uses the datetime.strptime function to parse the two timestamps and convert them into datetime objects. This function takes two arguments: the timestamp string and a string that defines the format of the timestamp. In this case, the timestamp format is "%a %d %b %Y %H:%M:%S %z", which stands for:

• `%a`: abbreviated weekday name
• `%d`: day of the month (01 to 31)
• `%b`: abbreviated month name
• `%Y`: year with century as a decimal number
• `%H`: hour (00 to 23)
• `%M`: minute (00 to 59)
• `%S`: second (00 to 59)
• `%z`: time zone offset from UTC

### Solution-2: Using dateutil module

Now we will use the `dateutil` module to solve the given problem:

``````import math
import os
import random
import re
import sys

# Complete the time_delta function below.
# importing the dateutil function
from dateutil.parser import parse
def time_delta(t1, t2):
return(str(abs(round((parse(t1)-parse(t2)).total_seconds()))))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

t = int(input())

for t_itr in range(t):
t1 = input()

t2 = input()

delta = time_delta(t1, t2)

fptr.write(delta + '\n')

fptr.close()
``````

The function first imports the `parse` function from the `dateutil` module, which is a powerful library for parsing dates and times in various formats. It then uses the `parse` function to parse the two timestamps and convert them into `datetime` objects.

Once the timestamps are converted to `datetime` objects, the function calculates the difference between them using the `timedelta.total_seconds` method and returns the absolute value of this difference as a string.

The rest of the code is similar to the previous example and is responsible for reading input from the user, calling the `time_delta` function with the input timestamps, and writing the output to a file.

### Solution-3: Using the split function

Now let us use the split function to solve the given problem: The following solution is similar to the first one except few changes.

``````import math
import os
import random
import re
import sys
from datetime import datetime

# Complete the time_delta function below.
def time_delta(t1, t2):
val1 = datetime.strptime(t1,"%a %d %b %Y %H:%M:%S %z")
val2 = datetime.strptime(t2,"%a %d %b %Y %H:%M:%S %z")
return (str(abs(val1-val2).total_seconds()).split("."))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

t = int(input())

for t_itr in range(t):
t1 = input()

t2 = input()

delta = time_delta(t1, t2)

fptr.write(delta + '\n')

fptr.close()
``````

Once the timestamps are converted to `datetime` objects, the function calculates the difference between them using the `timedelta.total_seconds` method and returns the absolute value of this difference as a string.

The rest of the code is similar to the previous examples, and is responsible for reading input from the user, calling the `time_delta` function with the input timestamps, and writing the output to a file. The output string is split at the "." and the first element is returned. This is done to remove the decimal portion of the output.

## Summary

In this article, we learned how we can solve Time Delta problem from HackerRank. We solved the problem using three different methods and we explained each method step by step.

Question on Hacker Rank: Date and Time (Python Delta Time)

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation. For any other feedbacks or questions you can either use the comments section or contact me form.