how to format datetie in python

To format datetime in Python, you can use the strftime method from the datetime module.

Here's an example that shows how to format a datetime object into a string:

main.py
from datetime import datetime

# Create a datetime object
dt = datetime(2022, 1, 15, 10, 30)

# Format datetime object as string
formatted_dt = dt.strftime("%Y-%m-%d %H:%M:%S")

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

In the above example, the strftime method is called on the dt datetime object to format it according to the specified format string "%Y-%m-%d %H:%M:%S". This format string defines the desired format, where %Y represents the year, %m represents the month, %d represents the day, %H represents the hour (24-hour format), %M represents the minute, and %S represents the second.

The output of the above code will be:

main.py
2022-01-15 10:30:00
20 chars
2 lines

You can modify the format string to match your desired datetime format.

Note that strftime only works for formatting datetime objects into strings. If you have a string representing a datetime and want to parse it into a datetime object, you can use the strptime method instead.

main.py
from datetime import datetime

# Parse a datetime string into a datetime object
dt_str = "2022-01-15 10:30:00"
dt = datetime.strptime(dt_str, "%Y-%m-%d %H:%M:%S")

print(dt)
174 chars
8 lines

The output will be:

main.py
2022-01-15 10:30:00
20 chars
2 lines

related categories

gistlibby LogSnag