7.2. Datetime ISO Standard

  • ISO 8601 is an International Standard [2]

7.2.1. Dates

  • Year-Month-Day

  • Format: YYYY-mm-dd

  • Example: 1969-07-21

Example:

  • 1961-04-12

  • 1969-07-21

  • 1999-12-31

  • 2000-01-01

7.2.2. Time

  • 24 hour clock

  • Format: HH:MM:SS.ffffff or HH:MM:SS or HH:MM

  • Example: 12:34, 12:34:56, 12:34:56.123456

  • Optional seconds and microseconds

  • 00:00 - midnight, at the beginning of a day

  • 23:59:59.999999 - midnight, at the end of a day

Example:

  • 00:00

  • 02:56:15

  • 13:00:00.123

  • 23:59:59.999999

7.2.3. Date and Time

  • Format: YYYY-mm-ddTHH:MM:SS.ffffff

  • Example: 1969-07-21T02:56:15.123456

  • "T" separates date and time)

  • Optional seconds and microseconds

Example:

  • 1969-07-21T02:56

  • 1969-07-21T02:56:15

  • 1969-07-21T02:56:15.123

  • 1969-07-21T02:56:15.123456

7.2.4. Timezone

  • Format: YYYY-mm-ddTHH:MM:SS.ffffff+0000

  • Format: YYYY-mm-ddTHH:MM:SS.ffffff+00:00

  • Format: YYYY-mm-ddTHH:MM:SS.ffffffUTC

  • Format: YYYY-mm-ddTHH:MM:SS.ffffffZ

  • Example: 1969-07-21T02:56:15.123456Z

  • Optional seconds and microseconds

  • "Z" (Zulu) means UTC

Time zone notation:

  • <time>UTC

  • <time>Z

  • <time>±hh:mm

  • <time>±hhmm

  • <time>±hh

Example:

  • 1969-07-21T02:56:15.123456Z

  • 1969-07-21T02:56:15.123456UTC

  • 1969-07-21T02:56:15.123456CEST

  • 1969-07-21T02:56:15.123456CET

  • 1969-07-21T02:56:15.123456+02:00

  • 1969-07-21T02:56:15.123456+0200

  • 1969-07-21T02:56:15.123456+02

7.2.5. Week

  • Format: YYYY-Www

  • The ISO 8601 definition for week 01 is the week with the first Thursday of the Gregorian year (i.e. of January) in it. [1]

  • 2000-W01 - 1st week of 2000

  • 2000-W53 - 53th week of 2000

7.2.6. Weekday

  • Format: YYYY-Www-dd

  • Week starts on Monday

  • ISO defines Monday as one

  • Note year/month changes during the week

  • 2000-W01-1 - Monday, January 3rd, 2000

  • 2009-W53-7 - Sunday, December 31st, 2010

>>> from datetime import datetime
>>>
>>>
>>> dt = datetime(1969, 7, 21, 2, 56, 15)
>>>
>>> dt.isoweekday()
1
>>>
>>> dt.weekday()
0

7.2.7. Duration

  • Format: P...Y...M...DT...H...M...S

  • Example: P8Y3M8DT20H49M15S

  • P - period - placed at the start of the duration representation

  • Y - number of years

  • M - number of months

  • W - number of weeks

  • D - number of days

  • T - precedes the time components of the representation

  • H - number of hours

  • M - number of minutes

  • S - number of seconds

P8Y3M8DT20H49M15S

8 years
3 months
8 days
20 hours
49 minutes
15 seconds

7.2.8. To ISO Format

  • datetime.isoformat()

  • date.isoformat()

  • time.isoformat()

Format to string in ISO-8601 standard:

>>> from datetime import date, time, datetime
>>>
>>>
>>> dt = datetime(1969, 7, 21, 2, 56, 15)
>>> d = date(1969, 7, 21)
>>> t = time(2, 56, 15)
>>>
>>> dt.isoformat()
'1969-07-21T02:56:15'
>>>
>>> dt.isoformat(' ')
'1969-07-21 02:56:15'
>>>
>>> d.isoformat()
'1969-07-21'
>>>
>>> t.isoformat()
'02:56:15'

7.2.9. From ISO Format

  • datetime.fromisoformat()

  • date.fromisoformat()

  • time.fromisoformat()

Parse from string in ISO-8601 standard:

>>> from datetime import date, time, datetime
>>>
>>>
>>> datetime.fromisoformat('1969-07-21T02:56:15')
datetime.datetime(1969, 7, 21, 2, 56, 15)
>>>
>>> date.fromisoformat('1969-07-21')
datetime.date(1969, 7, 21)
>>>
>>> time.fromisoformat('02:56:15')
datetime.time(2, 56, 15)

Note, that .fromisoformat() is fault-tolerant:

>>> from datetime import date, time, datetime
>>>
>>>
>>> datetime.fromisoformat('1969-07-21T02:56:15')
datetime.datetime(1969, 7, 21, 2, 56, 15)
>>>
>>> datetime.fromisoformat('1969-07-21 02:56:15')
datetime.datetime(1969, 7, 21, 2, 56, 15)
>>>
>>> date.fromisoformat('1969-07-21')
datetime.date(1969, 7, 21)
>>>
>>> time.fromisoformat('02:56:15')
datetime.time(2, 56, 15)
>>>
>>> time.fromisoformat('2:56:15')
Traceback (most recent call last):
ValueError: Invalid isoformat string: '2:56:15'
>>>
>>> time.fromisoformat('2:56')
Traceback (most recent call last):
ValueError: Invalid isoformat string: '2:56'

7.2.10. Use Case - 1

>>> from datetime import datetime
>>>
>>>
>>> line = '1969-07-21T02:56:15.123 [WARNING] First step on the Moon'
>>>
>>> dt, lvl, msg = line.split(maxsplit=2)
>>>
>>> result = {
...     'when': datetime.fromisoformat(dt),
...     'level': lvl.strip('[]'),
...     'message': msg.strip(),
... }
>>>
>>> print(result)  
{'when': datetime.datetime(1969, 7, 21, 2, 56, 15, 123000),
 'level': 'WARNING',
 'message': 'First step on the Moon'}

7.2.11. References

7.2.12. Assignments

# %% 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

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Datetime ISO Format
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Define `result: str` with `DATA` converted to ISO-8601 format
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: str` z przekonwertowaną `DATA` do formatu ISO-8601
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert type(result) is str, \
'Variable `result` has invalid type, must be a str'

>>> result
'1969-07-21T02:56:15'
"""

from datetime import datetime


DATA = datetime(1969, 7, 21, 2, 56, 15)

# DATA in ISO-8601 format: '1969-07-21T02:56:15'
# type: datetime
result = ...


# %% 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

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Datetime ISO Parse
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Define `result: datetime` with converted `DATA` from ISO-8601
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: datetime` z przekonwertowaną `DATA` z ISO-8601
# 2. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> assert type(result) is datetime, \
'Variable `result` has invalid type, must be a datetime'

>>> result
datetime.datetime(1969, 7, 21, 2, 56, 15, 123000)
"""

from datetime import datetime


DATA = '1969-07-21T02:56:15.123'

# DATA from ISO-8601 format
# type: datetime
result = ...


# %% 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

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Datetime ISO List
# - Difficulty: medium
# - Lines: 1
# - Minutes: 3

# %% English
# 1. Define `result: list[datetime]` with parsed `DATA` dates
# 2. Use list comprehension and `datetime.fromisoformat()`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: list[datetime]` ze sparsowanymi datami `DATA`
# 2. Skorzystaj z rozwinięcia listowego oraz `datetime.fromisoformat()`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `[x for x in DATA]`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from pprint import pprint
>>> result = list(result)

>>> assert type(result) is list, \
'Variable `result` has invalid type, must be a list'

>>> assert all(type(element) is datetime for element in result), \
'All elements in `result` must be a datetime'

>>> pprint(result, width=30)
[datetime.datetime(1961, 4, 12, 6, 7),
 datetime.datetime(1961, 4, 12, 6, 7)]
"""

from datetime import datetime

DATA = [
    '1961-04-12 06:07',
    '1961-04-12 06:07:00',
]

# parsed DATA
# type: list[datetime]
result = ...


# %% 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

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Datetime ISO Logs
# - Difficulty: medium
# - Lines: 7
# - Minutes: 13

# %% English
# 1. Iterate over `DATA` with Apollo 11 timeline [1]
# 2. From each line extract date, time, level and message
# 3. Collect data to `result: list[dict]` with keys:
#    - datetime: datetime
#    - level: Literal['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']
#    - message: str
# 4. Run doctests - all must succeed

# %% Polish
# 1. Iteruj po `DATA` z harmonogramem Apollo 11 [1]
# 2. Dla każdej linii wyciągnij datę, czas, poziom logowania oraz wiadomość
# 3. Zbierz dane do `result: list[dict]` z kluczami:
#    - datetime: datetime
#    - level: Literal['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']
#    - message: str
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `str.splitlines()`
# - `str.strip()`
# - `str.split(maxsplit)`
# - `date.fromisoformat()`
# - `time.fromisoformat()`
# - `datetime.combine()`
# - `list.append()`
# - Mind, time in last line don't have seconds, see NASA history records [1]

# %% References
# [1] National Aeronautics and Space Administration.
#     Apollo 11 timeline.
#     Year: 1969. Retrieved: 2021-03-25.
#     URL: https://history.nasa.gov/SP-4029/Apollo_11i_Timeline.htm

# %% Hints
# - `str.splitlines()`
# - `str.split()`
# - `str.split(', ', maxsplit=3)`
# - `date.fromisoformat()`
# - `time.fromisoformat()`
# - `datetime.combine()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from pprint import pprint
>>> result = list(result)

>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is list, \
'Variable `result` has invalid type, must be a list'
>>> assert all(type(row) is dict for row in result), \
'All elements in result must be dict'

>>> pprint(result)
[{'datetime': datetime.datetime(1969, 7, 14, 21, 0),
  'level': 'INFO',
  'message': 'Terminal countdown started'},
 {'datetime': datetime.datetime(1969, 7, 16, 13, 31, 53),
  'level': 'WARNING',
  'message': 'S-IC engine ignition (#5)'},
 {'datetime': datetime.datetime(1969, 7, 16, 13, 33, 23),
  'level': 'DEBUG',
  'message': 'Maximum dynamic pressure (735.17 lb/ft^2)'},
 {'datetime': datetime.datetime(1969, 7, 16, 13, 34, 44),
  'level': 'WARNING',
  'message': 'S-II ignition'},
 {'datetime': datetime.datetime(1969, 7, 16, 13, 35, 17),
  'level': 'DEBUG',
  'message': 'Launch escape tower jettisoned'},
 {'datetime': datetime.datetime(1969, 7, 16, 13, 39, 40),
  'level': 'DEBUG',
  'message': 'S-II center engine cutoff'},
 {'datetime': datetime.datetime(1969, 7, 16, 16, 22, 13),
  'level': 'INFO',
  'message': 'Translunar injection'},
 {'datetime': datetime.datetime(1969, 7, 16, 16, 56, 3),
  'level': 'INFO',
  'message': 'CSM docked with LM/S-IVB'},
 {'datetime': datetime.datetime(1969, 7, 16, 17, 21, 50),
  'level': 'INFO',
  'message': 'Lunar orbit insertion ignition'},
 {'datetime': datetime.datetime(1969, 7, 16, 21, 43, 36),
  'level': 'INFO',
  'message': 'Lunar orbit circularization ignition'},
 {'datetime': datetime.datetime(1969, 7, 20, 17, 44),
  'level': 'INFO',
  'message': 'CSM/LM undocked'},
 {'datetime': datetime.datetime(1969, 7, 20, 20, 5, 5),
  'level': 'WARNING',
  'message': 'LM powered descent engine ignition'},
 {'datetime': datetime.datetime(1969, 7, 20, 20, 10, 22),
  'level': 'ERROR',
  'message': 'LM 1202 alarm'},
 {'datetime': datetime.datetime(1969, 7, 20, 20, 14, 18),
  'level': 'ERROR',
  'message': 'LM 1201 alarm'},
 {'datetime': datetime.datetime(1969, 7, 20, 20, 17, 39),
  'level': 'WARNING',
  'message': 'LM lunar landing'},
 {'datetime': datetime.datetime(1969, 7, 21, 2, 39, 33),
  'level': 'DEBUG',
  'message': 'EVA started (hatch open)'},
 {'datetime': datetime.datetime(1969, 7, 21, 2, 56, 15),
  'level': 'WARNING',
  'message': '1st step taken lunar surface (CDR)'},
 {'datetime': datetime.datetime(1969, 7, 21, 2, 56, 15),
  'level': 'WARNING',
  'message': 'Neil Armstrong first words on the Moon'},
 {'datetime': datetime.datetime(1969, 7, 21, 3, 5, 58),
  'level': 'DEBUG',
  'message': 'Contingency sample collection started (CDR)'},
 {'datetime': datetime.datetime(1969, 7, 21, 3, 15, 16),
  'level': 'INFO',
  'message': 'LMP on lunar surface'},
 {'datetime': datetime.datetime(1969, 7, 21, 5, 11, 13),
  'level': 'DEBUG',
  'message': 'EVA ended (hatch closed)'},
 {'datetime': datetime.datetime(1969, 7, 21, 17, 54),
  'level': 'WARNING',
  'message': 'LM lunar liftoff ignition (LM APS)'},
 {'datetime': datetime.datetime(1969, 7, 21, 21, 35),
  'level': 'INFO',
  'message': 'CSM/LM docked'},
 {'datetime': datetime.datetime(1969, 7, 22, 4, 55, 42),
  'level': 'WARNING',
  'message': 'Transearth injection ignition (SPS)'},
 {'datetime': datetime.datetime(1969, 7, 24, 16, 21, 12),
  'level': 'INFO',
  'message': 'CM/SM separation'},
 {'datetime': datetime.datetime(1969, 7, 24, 16, 35, 5),
  'level': 'WARNING',
  'message': 'Entry'},
 {'datetime': datetime.datetime(1969, 7, 24, 16, 50, 35),
  'level': 'WARNING',
  'message': 'Splashdown (went to apex-down)'},
 {'datetime': datetime.datetime(1969, 7, 24, 17, 29),
  'level': 'INFO',
  'message': 'Crew egress'}]
"""
from datetime import date, datetime, time


DATA = """1969-07-14, 21:00:00, INFO, Terminal countdown started
1969-07-16, 13:31:53, WARNING, S-IC engine ignition (#5)
1969-07-16, 13:33:23, DEBUG, Maximum dynamic pressure (735.17 lb/ft^2)
1969-07-16, 13:34:44, WARNING, S-II ignition
1969-07-16, 13:35:17, DEBUG, Launch escape tower jettisoned
1969-07-16, 13:39:40, DEBUG, S-II center engine cutoff
1969-07-16, 16:22:13, INFO, Translunar injection
1969-07-16, 16:56:03, INFO, CSM docked with LM/S-IVB
1969-07-16, 17:21:50, INFO, Lunar orbit insertion ignition
1969-07-16, 21:43:36, INFO, Lunar orbit circularization ignition
1969-07-20, 17:44:00, INFO, CSM/LM undocked
1969-07-20, 20:05:05, WARNING, LM powered descent engine ignition
1969-07-20, 20:10:22, ERROR, LM 1202 alarm
1969-07-20, 20:14:18, ERROR, LM 1201 alarm
1969-07-20, 20:17:39, WARNING, LM lunar landing
1969-07-21, 02:39:33, DEBUG, EVA started (hatch open)
1969-07-21, 02:56:15, WARNING, 1st step taken lunar surface (CDR)
1969-07-21, 02:56:15, WARNING, Neil Armstrong first words on the Moon
1969-07-21, 03:05:58, DEBUG, Contingency sample collection started (CDR)
1969-07-21, 03:15:16, INFO, LMP on lunar surface
1969-07-21, 05:11:13, DEBUG, EVA ended (hatch closed)
1969-07-21, 17:54:00, WARNING, LM lunar liftoff ignition (LM APS)
1969-07-21, 21:35:00, INFO, CSM/LM docked
1969-07-22, 04:55:42, WARNING, Transearth injection ignition (SPS)
1969-07-24, 16:21:12, INFO, CM/SM separation
1969-07-24, 16:35:05, WARNING, Entry
1969-07-24, 16:50:35, WARNING, Splashdown (went to apex-down)
1969-07-24, 17:29, INFO, Crew egress"""

# representation of DATA; dict keys:
# - datetime: datetime
# - level: Literal['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']
# - message: str
# type: list[dict]
result = ...