How to Create a Time Object in Python 


               


How to Create a Time Object in Python



Python


In this article, we show how to create a time object in Python.

In Python, there is a datetime module which can create dates and times.

In this article, we will show how to create a time object, specifically, not a date object.

With a date object, we create a date, such as 6/15/1987

With a time object, we create a time, such as 3:45:12.

The 3 is the hour. 45 is the minutes. And 12 is the seconds.

So we'll show how to create a time object now in Python using the time class in the Python datetime module.

To create a time object, we use the time class in the datetime module using the statement, datetime.time(hour, minutes, seconds), where hour is the hour, minutes is the minutes, and seconds is the seconds.

In the following code below, we show how to create a time object, 3:45:12



So let's now go over this code.

So the first thing we have to do is import the datetime module. The datetime module allows us to create time objects in Python using the time class in the datetime module. The time class allows us to create time objects. We create an instance of the time class (which is a time object).

We then create a variable, time1. We set this equal to, datetime.time(3,45,12)

In order to create a time object with the datetime module, we pass into the datetime.time() function 3 parameters. The first 3 parameters are datetime.time(hour, minutes, seconds). We specify 3 for the hour, 45 for the minutes, and 12 for the seconds.

We then print out the time1 object, which is, 03:45:12

We then reference each element of the time object using attributes.

We reference the hour with the statement, time1.hour

We reference the minute with the statement, time1.minute

And we reference the second with the statement, time1.second

And this is how we can create a time object in Python using the time class of the datetime module.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...