To create a datetime object, the datetime module has to be imported. Next, date and time have to be added as arguments.
from datetime import datetime new_date = datetime(2020, 2, 13)
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:
new_date = datetime(2020, 2, 44)
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.
new_date = datetime(2020, 2, 13, 14, 26, 37)
You can print the whole datetime object:
The result is the whole date and time:
But you can also display part of it.
print(new_date.year) print(new_date.day) print(new_date.second)
The datetime object with the current date and time
To get the current date and time, use the now function of the datetime object.
from datetime import datetime current_date = datetime.now() print(current_date)
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.
from datetime import datetime date_from_string = datetime.strptime('5Feb2020', '%d%b%Y') print(date_from_string)
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.