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

You can use the strftime method from the datetime module in Python to format a date and time in the desired format.

Here is an example code snippet:

main.py
from datetime import datetime

now = datetime.now()
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S.%f')

print('Formatted date:', formatted_date)
148 chars
7 lines

In this code, we first import the datetime module and get the current date and time using the now() method. We then use the strftime() method to format the date in the desired format, which is specified using a string containing format codes. %Y represents the year (in 4 digits), %m represents the month (in 2 digits), %d represents the day (in 2 digits), %H represents the hour (in 24-hour format, in 2 digits), %M represents the minute (in 2 digits), %S represents the second (in 2 digits), and %f represents microseconds (in 6 digits).

The resulting formatted_date variable contains the date and time in the desired format, which can be printed or used further in the code.

gistlibby LogSnag