Yes, you're absolutely right! There are several other "simple format strings" or shorthand format codes similar to %F that combine multiple format codes into a single, convenient option. These are especially useful for common date and time formats.
Common Shorthand Format Codes:
| Code | Equivalent To | Description | Example Output |
|---|
%F | %Y-%m-%d | ISO 8601 date format | 2023-10-05 |
%T | %H:%M:%S | ISO 8601 time format | 14:30:45 |
%D | %m/%d/%y | US date format (MM/DD/YY) | 10/05/23 |
%R | %H:%M | 24-hour time (hours and minutes) | 14:30 |
%r | %I:%M:%S %p | 12-hour time with AM/PM | 02:30:45 PM |
%c | Locale's date and time | Full date and time | Thu Oct 5 14:30:45 2023 |
%x | Locale's date | Date only | 10/05/2023 |
%X | Locale's time | Time only | 14:30:45 |
Examples:
import datetime
dt = datetime.datetime(2023, 10, 5, 14, 30, 45)
print(dt.strftime('%F')) # 2023-10-05
print(dt.strftime('%T')) # 14:30:45
print(dt.strftime('%D')) # 10/05/23
print(dt.strftime('%R')) # 14:30
print(dt.strftime('%r')) # 02:30:45 PM
# Combined formats
print(dt.strftime('%F %T')) # 2023-10-05 14:30:45
print(dt.strftime('%F %R')) # 2023-10-05 14:30
Notes:
-
Locale Independence:
%F and %T are locale-independent (always the same format)
%D, %r, and %R are also consistent across locales
%c, %x, and %X are locale-dependent
-
ISO 8601 Combination:
- A common pattern is
%FT%T which gives you 2023-10-05T14:30:45 (ISO 8601 combined format)
-
POSIX Standard:
- These shorthand codes are part of the POSIX standard and work across most programming languages that implement strftime
-
Timezone Addition:
- You can add timezone information:
%F %T %z → 2023-10-05 14:30:45 +0000
These shorthand codes make formatting dates and times much more concise and readable in your code, especially when you're using standard formats like ISO 8601.