The Wayback Machine - https://web.archive.org/web/20240930194353/https://www.geeksforgeeks.org/python-program-to-find-difference-between-current-time-and-given-time/
Open In App

Python program to find difference between current time and given time

Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two times h1:m1 and h2:m2 denoting hours and minutes in 24 hours clock format. The current clock time is given by h1:m1. The task is to calculate the difference between two times in minutes and print the difference between two times in h:m format.

Examples:

Input : h1=7, m1=20, h2=9, m2=45 Output : 2 : 25 The current time is 7 : 20 and given time is 9 : 45. The difference between them is 145 minutes. The result is 2 : 25 after converting to h : m format. Input : h1=15, m1=23, h2=18, m2=54 Output : 3 : 31 The current time is 15 : 23 and given time is 18 : 54. The difference between them is 211 minutes. The result is 3 : 31 after converting to h : m format. Input : h1=16, m1=20, h2=16, m2=20 Output : Both times are same The current time is 16 : 20 and given time is also 16 : 20. The difference between them is 0 minutes. As the difference is 0, we are printing “Both are same times”.

Approach:

  • Convert both the times into minutes
  • Find the difference in minutes
  • Ff difference is 0, print “Both are same times”
  • Else convert difference into h : m format and print

Below is the implementation. 

Python
# Python program to find the
# difference between two times


# function to obtain the time
# in minutes form
def difference(h1, m1, h2, m2):
    
    # convert h1 : m1 into
    # minutes
    t1 = h1 * 60 + m1
    
    # convert h2 : m2 into
    # minutes
    t2 = h2 * 60 + m2
    
    if (t1 == t2):
        print("Both are same times")
        return
    else:
        
        # calculating the difference
        diff = t2-t1
        
    # calculating hours from
    # difference
    h = (int(diff / 60)) % 24
    
    # calculating minutes from
    # difference
    m = diff % 60

    print(h, ":", m)

# Driver's code
if __name__ == "__main__":
    
    difference(7, 20, 9, 45)
    difference(15, 23, 18, 54)
    difference(16, 20, 16, 20)

# This code is contributed by SrujayReddy

Output:

2 : 25
3 : 31
Both are same times

Time complexity: O(1) – the function only performs basic arithmetic operations which take constant time.

Auxiliary space: O(1) – the function uses a constant amount of memory to store the input variables, local variables, and output.


Previous Article
Next Article

Similar Reads

Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Python program to get Current Time
In this article, we will know the approaches to get the current time in Python. There are multiple ways to get it. The most preferably date-time module is used in Python to create the object containing date and time. Example 1: Current time of a timezone - Using pytZ module C/C++ Code from datetime import * import pytz tz_INDIA = pytz.timezone('Asi
2 min read
How to Get Current Date and Time using Python
In this article, we will cover different methods for getting data and time using the DateTime module and time module in Python. Different ways to get Current Date and Time using PythonCurrent time using DateTime objectGet time using the time moduleGet Current Date and Time Using the Datetime ModuleIn this example, we will learn How to get the curre
6 min read
Get current time in milliseconds using Python
In this article, we will get the time in milliseconds using Python. Here, we are using two inbuild modules of Python that is Datetime module and the Time Module to get the time in milliseconds. Get time in milliseconds using the DateTime module To get the time in milliseconds we used the DateTime module, Firstly we printed the date time with second
2 min read
Get Current Time in different Timezone using Python
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world's standard for time zone. In order to get the current time of different time zones, we will be using the pyt
4 min read
Python VLC MediaPlayer - Getting Current media time
In this article we will see how we can get current media time of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We can crea
2 min read
How to add hours to the current time in Python?
Prerequisites: Datetime module Every minute should be enjoyed and savored. Time is measured by the hours, days, years, and so on. Time helps us to make a good habit of organizing and structuring our daily activities. In this article, we will see how we can extract real-time from a python module. There are various ways to pass the date and time feat
3 min read
Python program to print current year, month and day
In this article, the task is to write a Python Program to print the current year, month, and day. Approach: In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date classCreate an object of the date classCall the today( ) function of date class to fetch
1 min read
Python program to print current hour, minute, second and microsecond
In this article, we are going to discuss how to print current hour, minute, second, and microsecond using Python. In order to print hour, minute and microseconds we need to use DateTime module in Python. Methods useddatetime.now().hour(): This method returns the current hour value of the datetime object.datetime.now().minute(): This method returns
4 min read
How to find the current capacity of a list in Python
List in Python is mainly implementation of dynamic sized arrays (like ArrayList in Java or vector in C++). Capacity of a list means number of elements a list can store at a specific time. When we append an element to a list, it will store the element if there is size is less than capacity. If current capacity exceeds, then lists resize and allocate
4 min read
Find current weather of any city using OpenWeatherMap API in Python
The OpenWeatherMap is a service that provides weather data, including current weather data, forecasts, and historical data to the developers of web services and mobile applications. It provides an API with JSON, XML, and HTML endpoints and a limited free usage tier. Making more than 60 calls per minute requires a paid subscription starting at USD 4
4 min read
How to get current CPU and RAM usage in Python?
CPU usage or utilization refers to the time taken by a computer to process some information. RAM usage or MAIN MEMORY UTILIZATION on the other hand refers to the amount of time RAM is used by a certain system at a particular time. Both of these can be retrieved using Python. Get current CPU usage in PythonGet current CPU usage using psutil The func
3 min read
Python | Create an empty text file with current date as its name
In this article, we will learn how to create a text file names as the current date in it. For this, we can use now() method of datetime module. The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute
1 min read
Get parent of current directory using Python
In Python, OS module is used to interact with the operating system. It comes under Python's standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system. OS module provides various ways for getting the parent di
4 min read
Change current working directory with Python
The OS module in Python is used for interacting with the operating system. This module comes under Python's standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by
2 min read
Get current Gold price using Python
In this article we will see how we can get the current gold price in India. There is a variation in price of gold with time to time, price of gold is moved by a combination of supply, demand, and investor behavior. That seems simple enough, yet the way those factors work together is sometimes counterintuitive. Modules required and Installation: Req
2 min read
Python - Elements Maximum till current index in List
Given list with elements, extract element if it's the maximum element till current index. Input : test_list = [4, 6, 7, 8] Output : [4, 6, 7, 8] Explanation : All elements are maximum till their index. Input : test_list = [6, 7, 3, 6, 8, 7] Output : [7, 8] Explanation : 7 and 8 are maximum till their index. Method #1 : Using loop This is brute meth
7 min read
Python - Get Today's Current Day using Speech Recognition
We often don't remember the day of the date due to our load of work we are doing. So, here is a Python program with the help of which we can find the day of the date with just a simple chat with our laptop or mobile. Modules NeededDateTime: This is a Library in Python with the help of which we can manipulate the date and time. It comes preinstalled
4 min read
Python VLC MediaPlayer - Getting length of current media
In this article we will see how we can get length of the current media of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. We
2 min read
Python VLC MediaPlayer - Getting Current State
In this article we will see how we can get current state of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. We can create
2 min read
Python VLC MediaPlayer – Getting Current Subtitle
In this article we will see how we can get the current subtitle of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. Subtitles
2 min read
Python VLC MediaPlayer – Getting Current Audio Track
In this article we will see how we can get the current audio track of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. For a
2 min read
Python VLC MediaPlayer – Setting Current Audio Track
In this article we will see how we can set the current audio track of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. For
2 min read
Python VLC MediaPlayer – Setting Current Audio Channel
In this article we will see how we can set the current audio channel of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. An a
2 min read
Python VLC MediaPlayer – Getting Current Audio Channel
In this article we will see how we can get the current audio channel of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. An a
2 min read
Python VLC MediaListPlayer - Getting Current State
In this article we will see how we can get current state of the MediaListPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Media list player is used to play multiple media in a row for example playing a series
2 min read
How to Get directory of Current Script in Python?
A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management. In this article, we will take a look at methods used for obtaining the Parent directory of the currently running python script, and would learn about va
4 min read
Get Current Value Of Generator In Python
Python generators are powerful constructs that allow lazy evaluation of data, enabling efficient memory usage and improved performance. When working with generators, it's essential to have tools to inspect their current state. In this article, we'll explore some different methods to get the current value of a generator in Python. Get Current Value
3 min read
Get Current directory in Python
In this article, we will cover How to Get and Change the Working Directory in Python. While working with file handling you might have noticed that files are referenced only by their names, e.g. 'GFG.txt' and if the file is not located in the directory of the script, Python raises an error. The concept of the Current Working Directory (CWD) becomes
3 min read
How to get the current username in Python
When building interacting Python programs you might need to get the current username for features like personalizing user experience, providing user-specific resources, Implementing robust logging and debugging, strengthening security, etc. We will use different Python modules and functions like os.getlogin(), os.path.expanduser(), environ.get() me
4 min read