8.1 Date Formatting

from datetime import datetime
 
def main():
 
  # Times and dates can be formatted using a set of predefined string
  # control codes 
  now = datetime.now() # get the current date and time
 
  # %y/%Y - Year, %a/%A - weekday, %b/%B - month, %d - day of month
  print now.strftime("%Y") # full year with century
  print now.strftime("%a, %d %B, %y") # abbreviated day, num, full month, abbreviated year
 
  # %c - locale's date and time, %x - locale's date, %X - locale's time
  print now.strftime("%c")
  print now.strftime("%x")
  print now.strftime("%X")
 
if __name__ == "__main__":
  main()

Firstly: %y/%Y - Year, %a/%A - weekday, %b/%B - month, %d - day of month

these are control codes, they are placeholders for fromatted output of a class method… In this case the datetime.now() method.

The .strftime("%Y") of datetime accepts any control code and replaces it with the actual value it represents.

Python also provides control codes for formatting the datetime output in the right format for the user's locale settings (Europe and NA format date and time differently… etc…):

%c - locale's date and time, %x - locale's date, %X - locale's time

8.2 Time formatting

Printing formatted time information works the same as the date information

from datetime import datetime
 
def main():
 
  # Times and dates can be formatted using a set of predefined string
  # control codes 
  now = datetime.now() # get the current date and time
 
  # %I/%H - 12/24 Hour, %M - minute, %S - second, %p - locale's AM/PM
  print now.strftime("%I:%M:%S %p") # 12-Hour:Minute:Second:AM
  print now.strftime("%H:%M") # 24-Hour:Minute
 
if __name__ == "__main__":
  main()