| 1 | #!/usr/bin/env python3 | Shebang (Unix/Linux/Mac). When you run the file directly (./script.py), the OS uses /usr/bin/env to look up python3 in your $PATH and executes the script with that interpreter. It’s ignored on Windows but harmless. |
| 2 | import datetime | Imports Python’s built-in datetime module, which supplies classes for manipulating dates and times. |
| 4 | def show_current_datetime(): | Starts the definition of a function named show_current_datetime. All indented lines that follow belong to this function until the indentation level goes back. |
| 5 | now = datetime.datetime.now() | Calls datetime.datetime.now() to grab the current local date-and-time as a datetime object and stores it in the variable now. |
| 6 | # Format: YYYY-MM-DD HH:MM:SS | Just a comment explaining what the next line does. Comments (text after #) are ignored by Python. |
| 7 | formatted = now.strftime("%Y-%m-%d %H:%M:%S") | Uses strftime (“string-format time”) to convert now into a string of the form YYYY-MM-DD HH:MM:SS. • %Y → 4-digit year• %m → 2-digit month (01-12)• %d → 2-digit day (01-31)• %H → hour in 24-h clock (00-23)• %M → minute (00-59)• %S → second (00-59) |
| 8 | print("Current date and time :") | Outputs the literal label line. |
| 9 | print(formatted) | Outputs the formatted date-time string created above. |
| 11 | if __name__ == "__main__": | Common Python idiom: The special variable __name__ is set to "__main__" only when the file is run as a script (e.g., python3 script.py). If the file is imported as a module in another script, this block is skipped. |
| 12 | show_current_datetime() | Calls the function, so the date and time get printed when the script is executed directly. |