To import the current date (year, month, day) and time (hour, minute, second), you have to import the datetime module.
1 |
import datetime |
Display date and time
First, let’s display the current date and time using the print function.
1 2 3 |
import datetime print(datetime.datetime.now()) |
This code will display both: the date and time:
2020-03-31 11:30:51.232310
This is the default format. After the second, there is a fraction of the second (the 1-microsecond precision).
Current date and time in the specified format
If you don’t like this format, you can change it to the exact format you like. To do it, you have to use the strftime function from the time module.
1 2 3 4 |
import time strings = time.strftime("%Y-%m-%d, %H:%M:%S") print(strings) |
This code returns this result:
2020-03-31, 13:17:40
Get the current year, month, day, hour, minute, and second separately
So far, we returned the current date and time in one print function.
If you want to have access to a single element, you can do it.
1 2 3 4 5 6 7 8 9 10 11 |
import datetime now = datetime.datetime.now() print(now.year) print(now.month) print(now.day) print(now.hour) print(now.minute) print(now.second) print(now.microsecond) |
For each result, we are using the print function. You can display even microseconds if you need them.
2020 3 31 13 24 15 397061