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.

ValueError: day is out of range for month

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:

2020-02-13 14:26:37

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:

2020-03-06 16:51:35.662081

The print function displays the 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:

2020-02-05 00:00:00

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