DEV Community

Cover image for Time Delta - HackerRank Python Solution
Deepak Raj
Deepak Raj

Posted on • Originally published at codeperfectplus.com on

3

Time Delta - HackerRank Python Solution

Time Delta is a medium difficulty problem that involves datetime manipulation and we have to return the absolute difference between in seconds. We will learn how to solve this problem in Python through a step-by-step tutorial in Python3.

Problem Statement and Explanation

Given two timestamps in the format Day dd Mon yyyy hh:mm:ss +xxxx where +xxxx represents the time zone. We have to print the absolute difference (in seconds) between them.

Suppose the first timestamp is Sun 10 May 2015 13:54:36 -0700 and the second timestamp is Sun 10 May 2015 13:54:36 -0000.

  • t1 = Sun 10 May 2015 13:54:36 -0700
  • t2 = Sun 10 May 2015 13:54:36 -0000

The absolute difference between them is 25200 seconds because the time zone offsets are -0700 and -0000 and then 7 hours is 25200 seconds. 7 * 3600 = 25200 seconds.

  • In the given solution, we will use the datetime module to convert the given string into a datetime object.
  • Then we will find the absolute difference between them and return the difference in seconds.

Time Delta Solution in Python

import datetime
def time_delta(t1, t2):
t1 = datetime.datetime.strptime(t1, "%a %d %b %Y %H:%M:%S %z")
t2 = datetime.datetime.strptime(t2, "%a %d %b %Y %H:%M:%S %z")
difference = int(abs(t1-t2).total_seconds())
return str(difference)
view raw time_delta.py hosted with ❤ by GitHub

Time Complexity of the Solution

The time complexity of the above solution is O(1) because we are using the datetime module to convert the given string into a datetime object and then we are finding the absolute difference between them and returning the difference in seconds.

Problem statement is taken from Hackerrank, and the solutions are implemented by CodePerfectPlus team

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay