How to Create a Datetime Object in Python



Python


In this article, we show how to create a datetime 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 datetime object, which is an object from the datetime module that stores both the date and time.

This is in contrast to a date object, which only stores the date. Or a time object, which only stores the time. A datetime object stores both the date and the time. So you can kind of look at it as a combination of a date object and a time object.

So in order to create a datetime object in Python, we import the datetime module and then we pass 6 parameters into the datetime.datetime() function, as follows, datetime.datetime(year, month, day, hour, minute, second)

So to create a datetime object, we pass in the year, month, day, hour, minute, and second.

In the following code below, we create a datetime object for 4/30/2016 3:20:06

This is April 30, 2016 at 3:20:06



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 a datetime object in Python using the datetime class in the datetime module. The datetime class allow us to create datetime objects. We create an instance of the datetime class (which is a datetime object).

We then create a variable, datetime1. We set this equal to, datetime.datetime(2016,4,30,3,20,6)

In order to create a datetime object with the datetime module, we pass into the datetime.time() function 6 parameters. The 6 parameters are datetime.datetime(year, month, day, hour, minutes, seconds). We specify 2016 for the year, 4 for the month (April), 30 for the day, 3 for the hour, 20 for the minutes, and 6 for the seconds.

We then print out the datetime1 object, which is, 2016-04-30 03:20:06

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

We reference the year with the statement, datetime1.year

We reference the month with the statement, datetime1.month

We reference the day with the statement, datetime1.day

We reference the hour with the statement, datetime1.hour

We reference the minute with the statement, datetime1.minute

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

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


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...