To import the current date (year, month, day) and time (hour, minute, second), you have to import the datetime module.
Display date and time
First, let’s display the current date and time using the print function.
import datetime print(datetime.datetime.now())
This code will display both: date and time:
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.
import time strings = time.strftime("%Y-%m-%d, %H:%M:%S") print(strings)
This code returns this result:
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.
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