Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Input and Output

Print formatted date using f-strings - Python Program

Example 1:

day = 5 month = "August" year = 2025 print(f"Today's date is: {day} {month}, {year}")

Output

 
OUTPUT  :
Today's date is: 5 August, 2025 

Example 2: Advanced

from datetime import datetime # Get the current date and time now = datetime.now() # Example 1: Basic date and time formatting print(f"Today's date is {now:%Y-%m-%d} and the time is {now:%H:%M:%S}.") # Example 2: Displaying full month name and weekday print(f"It's {now:%A}, {now:%B} {now:%d}, {now:%Y}.") # Example 3: Date only in a common format print(f"Current date: {now:%m/%d/%y}") # Example 4: Time only print(f"Current time: {now:%I:%M %p}")

Output

 
OUTPUT  :
Today's date is 2025-08-06 and the time is 06:53:52.
It's Wednesday, August 06, 2025.
Current date: 08/06/25
Current time: 06:53 AM 

Explanation:

  • from datetime import datetime:

This line imports the datetime class from the datetime module, which is necessary to work with dates and times.

  • now = datetime.now():

This creates a datetime object representing the current date and time and assigns it to the now variable.

  • F-string Syntax with Date Formatting:

Inside the f-string, within the curly braces {}, the datetime object (now) is followed by a colon : and then the desired format specifiers.

  • %Y: Full year (e.g., 2025)
  • %m: Month as a zero-padded 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 (00-23)
  • %M: Minute as a zero-padded decimal number (00-59)
  • %S: Second as a zero-padded decimal number (00-59)
  • %A: Full weekday name (e.g., Wednesday)
  • %B: Full month name (e.g., August)
  • %y: Year without century as a zero-padded decimal number (00-99)
  • %I: Hour (12-hour clock) as a zero-padded decimal number (01-12)
  • %p: Locale's equivalent of either AM or PM.

 

By combining these format specifiers, various date and time representations can be achieved within f-strings for clear and concise output.