Show current time with python

Here’s a Python 2 code snippet that shows the current time in the format of YYYY-MM-dd HH:mm:ss:

1
2
3
4
5
6
import datetime

now = datetime.datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:%S")

print(current_time)

First, we import the datetime module, which gives us access to the date and time-related functions in Python. Then, we call datetime.datetime.now() to get the current date and time, and store it in the now variable.

Next, we use the strftime() method to format the date and time as a string. In this particular case, we’re using the format string “%Y-%m-%d %H:%M:%S”, which represents the year, month, and day in the format of YYYY-MM-DD, followed by the hours, minutes, and seconds in the format of HH:mm:ss.

Finally, we print the formatted date and time to the console using the print() function. The output will be in this format: 2016-05-13 10:40:10