How To Take Time Input In Python

In this tutorial, you will learn how to take time input in Python, allowing you to work with specific time values. Time is a crucial component in many applications, such as scheduling programs, timers, and managing dates.

Having a clear understanding of how to take time input in Python can make your programs more robust and efficient. We will be using the datetime module that comes with Python which makes working with time much more manageable.

Step 1: Import the datetime module

The first step is to import the datetime module, which provides the necessary functions and classes to work with dates and times.

Step 2: Get user input

Next, you need to get the time input from the user in the form of a string. You can use the built-in input() function for this purpose.

Step 3: Use strptime() method to parse the input string

After getting the user’s input, you must convert the inputted string into a datetime.time object. The datetime.strptime() method can do this by using a custom format string that matches the time format.

The datetime.datetime.strptime() method takes two arguments:

  1. The first argument is the time string that the user has inputted (time_input in this case).
  2. The second argument is the format string you use to specify how the input string should be parsed. In our example, we use "%H:%M:%S" as the format string, which means the input is expected as hours, minutes, and seconds separated by colons.

After conversion, the method returns a datetime.datetime object, which has a .time() method that extracts a datetime.time object representing the time in the input string.

Step 4: Display the inputted time

Finally, you can display the inputted time in the format you prefer, using the strftime() method.

The strftime() method converts the datetime.time object into a formatted string. The first argument is a format string, which specifies how the output string should be formatted. In this example, we use "%H:%M:%S" as the format string to display the time in hours, minutes, and seconds.

Here’s the full code:

When you run the code, it should display a prompt to enter the time:

Enter time in hh:mm:ss format: 12:34:56
Entered time: 12:34:56

Conclusion

Now you know how to take time input in Python using the datetime module. You can further customize the format string to work with different time formats according to your application’s needs. The key is to understand the strptime() and strftime() methods to parse and format time values consistently. For additional information on working with time in Python, visit the official Python datetime documentation.