To format a date in Python, you can make use of the strftime()
method that is available through the datetime
module. The strftime()
method allows you to format dates into various string representations.
To format a date in the format month day, year hour:minute:second am/pm
, you can use the following code:
main.py203 chars10 lines
In the code above, we are first creating a datetime
object representing the current date and time. We then use the strftime()
method to format the date using the specified format string.
The format string used in the code above breaks down as follows:
%B
: Full month name%d
: Day of the month (zero-padded)%Y
: Year (four digits)%I
: Hour (12-hour clock)%M
: Minute%S
: Second%p
: AM/PM designationThe resulting string is then printed to the console. The output would look something like this:
main.py45 chars2 lines
gistlibby LogSnag