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

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

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 sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay