How do you use the FORMAT function to format dates and numbers?
Posted by HenryPk
Last Updated: June 27, 2024
The FORMAT function is a versatile tool in many programming languages and data analysis tools for formatting dates and numbers into a specific string format. Below are examples of how to use the FORMAT function in different contexts, specifically in SQL Server, Microsoft Excel, and Python.
SQL Server
In SQL Server, you can use the FORMAT function to format dates and numbers.
Formatting Dates:
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS FormattedDate;
-- Output: 2023-10-05 (example output based on the current date)
Formatting Numbers:
SELECT FORMAT(12345.6789, 'C', 'en-US') AS FormattedCurrency;
-- Output: $12,345.68 (formatted as currency)
Microsoft Excel
In Excel, the TEXT function is often used to format dates and numbers, but FORMAT can also refer to custom number formatting.
Formatting Dates:
=TEXT(A1, "yyyy-mm-dd") -- Assuming A1 contains a date
Formatting Numbers:
=TEXT(A1, "$#,##0.00") -- Assuming A1 contains a number
Python
In Python, you can use the format function or f-strings for formatting.
Formatting Dates:
Using the datetime module:
from datetime import datetime

now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d")
print(formatted_date)  # Output: 2023-10-05 (example output)
Formatting Numbers:
Using f-strings:
number = 12345.6789
formatted_number = f"{number:,.2f}"
print(formatted_number)  # Output: 12,345.68
Key Points
- Date Format Codes: Formatting for dates commonly involves format codes like yyyy, MM, dd, HH, mm, ss, etc., depending on the language or tool. - Number Format Codes: For numbers, you can use codes for decimal places, commas for thousands separators, and currency symbols as needed. When using the FORMAT function (or similar functions) in your specific tool or programming language, consult the relevant documentation for more detailed format strings and options.