Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Time
Date
Datetime
13. Formatting datetimes
Summary

Instruction

Great!

When we use print(datetime), we see datetimes in the following format:

2018-12-01 09:45:00

However, we may want to use another format. To that end, we can apply the strftime() function. Take a look:

fra_mad_1_Dec = datetime.datetime(2018, 12, 1, 8, 15, 0)
print('Boarding starts at', fra_mad_1_Dec.strftime('%H:%M on %A, %d %B %Y'))

Result:

Boarding starts at 08:15 on Saturday, 01 December 2018

The datetime.strftime() function allows us to specify the exact output format of a datetime object. In the example above, we used the following elements:

  • %H – hour (24-hour clock)
  • %M – minutes
  • %A – weekday (full name)
  • %d – zero-padded day of the month
  • %B – month's full name
  • %Y – year

We can swap the order of elements, add various characters between them, or change the elements themselves.

We highly recommend you take a look at Python's official documentation or at this site with memorable URL, which lists all possible formatting elements.

Exercise

Create a function named format_meeting(meeting_title, meeting_start), where meeting_title is a string and meeting_start is a datetime.

For the following invocation:

format_meeting("Budget review", datetime.datime(2018, 10, 5, 13, 30))

the function should return a string that contains meeting information in the following format:

Budget review - Fri, 05 Oct 2018, 01:30 PM

Use the following formatting elements:

  • %a – weekday (abbreviated)
  • %d – day of month
  • %b – month (abbreviated)
  • %Y – year
  • %I – hour (12-hour clock)
  • %M – minutes
  • %p – AM or PM

You can use the sample_meeting_title and sample_meeting_datetime variables to test your function.

Stuck? Here's a hint!

Use:

strftime('%a, %d %b %Y, %I:%M %p')