Creating datetime in Python

To create a datetime object, the datetime module has to be imported. Next, date and time have to be added as arguments.

The code above takes three arguments: year (2020), month (2), day (13).

You have to remember that these values have to be inside certain ranges. Try to write the code this way:

If you try to execute this code, you are going to get an error.

Adding time to datetime

The datetime function can take additional arguments: hour, minute, and second.

You can print the whole datetime object:

The result is the whole date and time:

But you can also display part of it.

The datetime object with the current date and time

To get the current date and time, use the now function of the datetime object.

Take a look at the result:

The print function displays date and time. But there is also one additional number. This is the decimal fraction of a second, namely microsecond. You can add this as an argument of datetime, after the second. It can be accessed this way:

Create a datetime object from a string

If you work with files, the data is not always formatted the way you want. To deal with this problem, datetime offers a function called strptime.

The first argument is a string, and the second one is a way to describe how the string should be formatted.

If you print the object you will have this result:

There is no time inside an argument, so by default, the time is midnight.