Date & Time


The easiest way to state the current time and date is to use the ctime() command. Remember to import the ctime command from the time library before you use and print it:


This will print the time and date but it looks rather unprofessional and the exact format depends on the type of system that you are currently running so it may vary for different users. It may look like this:

date 2

If you just want to print the current time and date and you are not fussed about aesthetics (how it looks) then you can use the ctime command easily within your programs. An example:


This could run as:



If you want to customise which aspects of the date and time that you want to display then you can use the strftime() command. This command requires a directive to be written as a string in the brackets. For example:


This would print the current hour : minute : second; such as:

date 6.PNG

There are many different directives that you can use to display exactly what you are looking for, such as:

date7The code above could output the following:


You can show more than one directive in the same strftime command. The following example shows an improved dentist surgery program that now displays the current hour in 12-hour clock (%I), the current minute (%M) and whether it is AM or PM (%p):


The above code could output the following:


Below are some of the directives that you can use to display the date and time:


%a – Current day of the week abbreviated (e.g. Sun, Mon)
%A – Current day of the week in full (e.g. Sunday, Monday)
%w – Current day of the week in chronological order (0 is Sunday and 6 is Saturday)
%W – Current week number (e.g. 01, 26, 52)

%d – Current day of the month (e.g. 01, 11, 31)
%m – Current month as a number (e.g. 01, 06, 12)
%b – Current month abbreviated (e.g. Jan, Jun, Dec)
%B – Current month in full (e.g. January, December

%y – Current year abbreviated (e.g. 16, 17)
%Y – Current year in full (e.g. 2016, 2017)
%j – Current day of the year (e.g. 001, 150, 365)


%H – Current hour in 24-hour clock (e.g. 00, 12, 20)
%I – Current hour in 12-hour clock (e.g. 01, 08, 12)
%p – Whether it is currently AM or PM

%M – Current minute (e.g. 00, 30, 59)

%S – Current second (e.g. 00, 30, 59)

More directives

%z – Current time difference from UTC (Co-ordinated Universal Time) (e.g. +0000, -0500, +1100)
%Z – Current time zone (e.g. GMT Standard Time, EST, CST)

Just looking for a quick date or time display and not bothered about customisation? Try these:

%c – Current date and time in full (e.g. Tue Feb 19 13:35:20 2016)
%x – Current date (e.g. 19/02/16)
%X – Current time (13:36:20)

Date and Time not working? Tick off these common errors:

< Back to Section Five