format a datetime from 2023-01-01 00:00:00 to '11-may-2023' in python

You can use the strftime method from the datetime module in Python to format a datetime object. Here's an example of how to format a datetime from 2023-01-01 00:00:00 to '11-may-2023':

main.py
from datetime import datetime

# Create a datetime object
dt = datetime.strptime('2023-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')

# Format the datetime object
formatted_dt = dt.strftime('%d-%b-%Y')

# Print the formatted datetime
print(formatted_dt)
246 chars
11 lines

This will output: 11-May-2023

In the strftime method, %d represents the day, %b represents the abbreviated month name, and %Y represents the four-digit year. Make sure to include the leading zero for the day (%d) to get a two-digit day, i.e., 11 instead of just 1.

related categories

gistlibby LogSnag