To create a datetime object, the datetime module has to be imported. Next, date and time have to be added as arguments.
1 2 |
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:
1 |
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.
1 |
new_date = datetime(2020, 2, 13, 14, 26, 37) |
You can print the whole datetime object:
1 |
print(new_date) |
The result is the whole date and time:
2020-02-13 14:26:37
But you can also display part of it.
1 2 3 |
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.
1 2 3 4 |
from datetime import datetime current_date = datetime.now() print(current_date) |
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:
1 |
print(current_date.microsecond) |
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.
1 2 3 4 |
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:
2020-02-05 00:00:00
There is no time inside an argument, so by default, the time is midnight.