How to Convert Time in Python?

Estimated read time 2 min read

To convert time in Python, you can use the datetime module, which provides functions for working with dates and times. Here are a few common scenarios for converting time:

  1. String to Time: If you have a time string and want to convert it to a time object, you can use the datetime.strptime() function with the appropriate format code.
from datetime import datetime

time_str = "12:34:56"  # Example time string
format_code = "%H:%M:%S"  # Format code for the time string

time_obj = datetime.strptime(time_str, format_code).time()
print(time_obj)

In this example, we directly use the time() constructor and pass the hour, minute, and second as arguments. This creates a time object representing the specified time, which we assign to the time_obj variable. Finally, we print the time_obj.

  1. Current Time: If you want to get the current time, you can use the datetime.now() function and access the time() method.
from datetime import datetime

current_time = datetime.now().time()
print(current_time)

In this example, we use the datetime.now() function to get the current date and time as a datetime object. Then, we access the time() method to extract the time object representing the current time. Finally, we print the current_time.

Choose the appropriate approach based on your specific requirements. The time object allows you to work with time-specific operations and formatting in Python.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply