format a date in to the format 'yyyy-mm-dd hh:mm:ss' in python

To format a date in yyyy-mm-dd hh:mm:ss format in Python, you can use the strftime() method of the datetime object. Here's an example code block:

main.py
from datetime import datetime

# get current date and time
now = datetime.now()

# format date and time as string
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')

# print formatted date string
print('Current date and time: {}'.format(formatted_date))
254 chars
11 lines

In this code block, we first import the datetime module to work with dates and times. We then create a datetime object representing the current date and time using the now() method.

Next, we format the date and time as a string using the strftime() method. The %Y specifier represents the year in four digits, %m represents the month in two digits, %d represents the day in two digits, %H represents the hour in 24-hour format, %M represents the minute in two digits, and %S represents the second in two digits. We concatenate these specifiers with hyphens and spaces to create our desired format.

Finally, we print the formatted date and time string.

gistlibby LogSnag