To format a date in Python, you can use the datetime
module and the strftime()
method.
Here's an example:
main.py293 chars12 lines
Output:
main.py70 chars3 lines
In the strftime()
method, you specify the format string that represents the desired output format. You can use a combination of letters and special characters to define the format. Some popular format codes are:
%Y
: year with century as a decimal number.%m
: month as a decimal number (01 - 12).%d
: day of the month as a zero-padded decimal number (01 - 31).%H
: hour (24-hour clock) as a zero-padded decimal number.%M
: minute as a zero-padded decimal number.%S
: second as a zero-padded decimal number.%a
: abbreviated name of the day of the week.%A
: full name of the day of the week.%b
: abbreviated month name.%B
: full month name.%c
: date and time representation (e.g. 'Mon Sep 30 07:06:05 2013').%p
: locale’s equivalent of either AM or PM.You can read more about formatting options in the official documentation.
gistlibby LogSnag