Search code examples
pythonpython-datetimeisodate

Why does datetime.now().isoformat() return an invalid isoformat string according to time.fromisoformat()?


Running Python 3.8.10, came across this today:

from datetime import datetime, time
time.fromisoformat(datetime.now().isoformat())

Results in:

Traceback (most recent call last): ValueError: Invalid isoformat string: '2021-09-02T17:16:49.330690'

Why is an isoformat string created by the datetime.datetime module considered invalid by the datetime.time module?


Solution

  • Because datetime.now gives you a date and a time, whereas time.fromisoformat wants a time string only.

    From the time.fromisoformat documentation:

    Caution

    This does not support parsing arbitrary ISO 8601 strings. It is only intended as the inverse operation of time.isoformat().

    Try again with

    datetime.now().time() instead.