The datetime module gives you the current date and time. datetime.now() returns the date and the time together, and date.today() returns only the date.
The program
python
from datetime import date, datetime now = datetime.now() print("Now: ", now) print("Today:", date.today()) if now.hour < 12: greeting = "Good morning" elif now.hour < 18: greeting = "Good afternoon" else: greeting = "Good evening" print(f"{greeting}. It is {now:%A %d %B %Y, %H:%M}.")
example output · yours will differ
Now: 2026-10-22 14:05:37.512894 Today: 2026-10-22 Good afternoon. It is Thursday 22 October 2026, 14:05.
The output above is from one run. Your output shows the date and time when you run it.
How it works
datetime.now()reads the computer's clock and returns adatetimeobject. Printing it shows the date, the time and the microseconds.now.houris a whole number from 0 to 23, so theifchain can choose the greeting.{now:%A %d %B %Y, %H:%M}formats the date inside an f-string. The codes after the colon are the same as the onesstrftime()uses.datetime.now()gives the local time of the computer. For times you save or send to another computer, usedatetime.now(timezone.utc)(importtimezonefromdatetimetoo).
Format codes
strftime() turns a date into text. This example uses a fixed date and time, so the output is always the same:
python
from datetime import datetime moment = datetime(2026, 10, 22, 14, 5, 37) # fixed; use datetime.now() in real use formats = [ "%Y-%m-%d", "%d/%m/%Y", "%A %d %B %Y", "%a %d %b", "%H:%M:%S", "%I:%M %p", ] for code in formats: print(f"{code:<12} {moment.strftime(code)}")
output
%Y-%m-%d 2026-10-22 %d/%m/%Y 22/10/2026 %A %d %B %Y Thursday 22 October 2026 %a %d %b Thu 22 Oct %H:%M:%S 14:05:37 %I:%M %p 02:05 PM
%Yis the four-digit year,%mthe month number and%dthe day, each with a leading zero when needed.%Aand%Bgive the full day and month names.%aand%bgive the short names.%His the 24-hour clock.%Iwith%pis the 12-hour clock with AM or PM.- Day and month names follow the computer's language settings, so on some computers they may not be in English.
To turn text back into a date, see the days between dates program, which uses date.fromisoformat().