To import the current date (year, month, day) and time (hour, minute, second), you have to import the datetime module.
import datetime
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:
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.
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.
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