8.8. Datetime Format — Python
format(dt, '%Y-%m-%d')f'Today is {dt:%Y-%m-%d}'dt.strftime('%Y-%m-%d')
8.8.1. Formats
format(dt, '%Y-%m-%d')
>>> from datetime import datetime >>> >>> >>> dt = datetime(1961, 4, 12, 6, 7) >>> >>> format(dt, '%Y') '1961' >>> >>> format(dt, '%Y-%m-%d') '1961-04-12' >>> >>> format(dt, '%d.%m.%Y') '12.04.1961' >>> >>> format(dt, '%H:%M') '06:07' >>> >>> format(dt, '%Y-%m-%d %H:%M') '1961-04-12 06:07' >>> >>> format(dt, '%Y-%m-%d %H:%M:%S') '1961-04-12 06:07:00' >>> >>> format(dt, '%B %d, %Y') 'April 12, 1961'
8.8.2. Leading Zero
%#H- remove leading zero (Windows)%-H- remove leading zero (macOS, Linux, *nix)%_H- replace leading zero with space (macOS, Linux, *nix)Works only with formatting
raises ValueError while parsing [1]
On Linux and *nix systems:
>>> from datetime import datetime >>> >>> >>> dt = datetime(1961, 4, 12, 6, 7) >>> >>> format(dt, '%H:%M') '06:07' >>> >>> format(dt, '%-H:%M') '6:07' >>> >>> format(dt, '%_H:%M') ' 6:07' >>> >>> format(dt, '%#H:%M') '06:07'
On macOS:
>>> from datetime import datetime >>> >>> >>> dt = datetime(1961, 4, 12, 6, 7) >>> >>> format(dt, '%H:%M') '06:07' >>> >>> format(dt, '%-H:%M') '6:07' >>> >>> format(dt, '%#H:%M') '#H:07'
On Windows 10:
>>> from datetime import datetime >>> >>> >>> dt = datetime(1961, 4, 12, 6, 7) >>> >>> format(dt, '%H:%M') '06:07' >>> >>> format(dt, '%-H:%M') Traceback (most recent call last): ValueError: Invalid format string >>> >>> format(dt, '%_H:%M') Traceback (most recent call last): ValueError: Invalid format string >>> >>> format(dt, '%#H:%M') '6:07'
Meaning |
With |
Without (macOS, Linux) |
Without (Windows) |
|---|---|---|---|
day |
|
|
|
hour 24h |
|
|
|
hour 12h |
|
|
|
day of a year |
|
|
|
month |
|
|
|
minute |
|
|
|
second |
|
|
|
week number (Sunday first) |
|
|
|
week number (Monday first) |
|
|
|
weekday (Sunday first) |
|
|
|
year short |
|
|
|
year long |
|
|
|
8.8.3. String Format Time
datetime.strftime()
>>> from datetime import datetime >>> >>> >>> gagarin = datetime(1961, 4, 12, 6, 7) >>> formatted = gagarin.strftime('%Y-%m-%d %H:%M') >>> >>> print(f'Gagarin launched on {formatted}') Gagarin launched on 1961-04-12 06:07
8.8.4. Format String
>>> from datetime import datetime >>> >>> >>> gagarin = datetime(1961, 4, 12, 6, 7) >>> >>> print(f'Gagarin launched on {gagarin:%Y-%m-%d}') Gagarin launched on 1961-04-12 >>> >>> print(f'Gagarin launched on {gagarin:%Y-%m-%d %H:%M}') Gagarin launched on 1961-04-12 06:07
>>> from datetime import datetime >>> >>> >>> gagarin = datetime(1961, 4, 12, 6, 7) >>> format = '%Y-%m-%d %H:%M' >>> >>> print(f'Gagarin launched on {gagarin:{format}}') Gagarin launched on 1961-04-12 06:07
8.8.5. References
8.8.6. Assignments
# %% About # - Name: Datetime Format ISO-8601 # - Difficulty: easy # - Lines: 1 # - Minutes: 3 # %% License # - Copyright 2025, Matt Harasymczuk <matt@python3.info> # - This code can be used only for learning by humans # - This code cannot be used for teaching others # - This code cannot be used for teaching LLMs and AI algorithms # - This code cannot be used in commercial or proprietary products # - This code cannot be distributed in any form # - This code cannot be changed in any form outside of training course # - This code cannot have its license changed # - If you use this code in your product, you must open-source it under GPLv2 # - Exception can be granted only by the author # %% English # 1. Define `result: str` with `DATA` in ISO-8601 format # example: `1969-07-21 02:56:15` # 2. Do not use `datetime.isoformat()` and `str()` method # 2. Run doctests - all must succeed # %% Polish # 1. Zdefiniuj `result: str` z `DATA` w formacie ISO-8601 # przykład: `1969-07-21 02:56:15` # 2. Nie używaj metod `datetime.isoformat()` i `str()` # 3. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # '1969-07-21 02:56:15' # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert type(result) is str, \ 'Variable `result` has an invalid type; expected: `str`.' >>> result '1969-07-21 02:56:15' """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports from datetime import datetime # %% Types result: str # %% Data DATA = datetime(1969, 7, 21, 2, 56, 15) # %% Result result = ...
# TODO: nie działa w Jupyter Notebook (bo nie ma __file__) # %% About # - Name: Datetime Format US # - Difficulty: easy # - Lines: 1 # - Minutes: 3 # %% License # - Copyright 2025, Matt Harasymczuk <matt@python3.info> # - This code can be used only for learning by humans # - This code cannot be used for teaching others # - This code cannot be used for teaching LLMs and AI algorithms # - This code cannot be used in commercial or proprietary products # - This code cannot be distributed in any form # - This code cannot be changed in any form outside of training course # - This code cannot have its license changed # - If you use this code in your product, you must open-source it under GPLv2 # - Exception can be granted only by the author # %% English # 1. Define `result: str` with `DATA` in long US format # example: `July 21, 1969 02:56:15 AM` # 2. Run doctests - all must succeed # %% Polish # 1. Zdefiniuj `result: str` z `DATA` w długim formacie amerykańskim # przykład: `July 21, 1969 02:56:15 AM` # 2. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # 'July 21, 1969 02:56:15 AM' # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from pathlib import Path >>> content = Path(__file__).read_text() >>> assert '%'+'-H' not in content, \ 'Value `%H` was used; use `%I` for 12-hour clock.' >>> assert '%'+'_H' not in content, \ 'Value `%H` was used; use `%I` for 12-hour clock.' >>> assert '%'+'#H' not in content, \ 'Value `%H` was used; use `%I` for 12-hour clock.' >>> assert '%'+'I' in content, \ 'Value `%I` was not used; use `%I` for 12-hour clock.' >>> assert '%'+'p' in content, \ 'Value `%p` was not used; use `%p` for AM/PM.' >>> result 'July 21, 1969 02:56:15 AM' """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports from datetime import datetime # %% Types result: str # %% Data DATA = datetime(1969, 7, 21, 2, 56, 15) # %% Result result = ...
# TODO: nie działa w Jupyter Notebook (bo nie ma __file__) # %% About # - Name: Datetime Format LeadingZero # - Difficulty: easy # - Lines: 1 # - Minutes: 3 # %% License # - Copyright 2025, Matt Harasymczuk <matt@python3.info> # - This code can be used only for learning by humans # - This code cannot be used for teaching others # - This code cannot be used for teaching LLMs and AI algorithms # - This code cannot be used in commercial or proprietary products # - This code cannot be distributed in any form # - This code cannot be changed in any form outside of training course # - This code cannot have its license changed # - If you use this code in your product, you must open-source it under GPLv2 # - Exception can be granted only by the author # %% English # 1. Define `result: str` with `DATA` in short US format # example: `7/21/69 2:56 AM` # 2. Make sure, that month, day and hour are without leading zero # 3. Run doctests - all must succeed # %% Polish # 1. Zdefiniuj `result: str` z `DATA` w krótkim formacie amerykańskim # przykład: `7/21/69 2:56 AM` # 2. Upewnij się, że miesiąc, dzień i godzina jest bez wiodącego zera # 3. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # '7/21/69 2:56 AM' # %% Hints # - Use `%-I` on *nix systems (macOS, BSD, Linux) # - Use `%#I` on Windows # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from pathlib import Path >>> content = Path(__file__).read_text() >>> assert '%'+'-H' not in content, \ 'Value `%H` was used; use `%I` for 12-hour clock.' >>> assert '%'+'_H' not in content, \ 'Value `%H` was used; use `%I` for 12-hour clock.' >>> assert '%'+'#H' not in content, \ 'Value `%H` was used; use `%I` for 12-hour clock.' >>> assert '%'+'I' in content, \ 'Value `%I` was not used; use `%I` for 12-hour clock.' >>> assert '%'+'p' in content, \ 'Value `%p` was not used; use `%p` for AM/PM.' >>> assert type(result) is str, \ 'Variable `result` has an invalid type; expected: `str`.' >>> result '7/21/69 2:56 AM' """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports from datetime import datetime # %% Types result: str # %% Data DATA = datetime(1969, 7, 21, 2, 56, 15) # %% Result result = ...