1
from datetime import datetime, time
from zoneinfo import ZoneInfo

time(8, 37, 9, tzinfo=ZoneInfo("UTC")).isoformat()
# '08:37:09+00:00'

datetime.utcnow().isoformat()
# 2023-07-13T08:37:09.033778

time(8, 37, 9, 33778).isoformat()
# 08:37:09.033778

time(8,37,9, 33778, ZoneInfo("UTC")).isoformat()
# 08:37:09.033778+00:00

I was expecting to have a constant isoformat. (end of datetime.isoformat() = time.isoformat())

Is there any explanation ?

Mathieu B.
  • 51
  • 4
  • 1
    see [Stop using utcnow and utcfromtimestamp](https://blog.ganssle.io/articles/2019/11/utcnow.html) - if you want a UTC datetime, use [aware datetime](https://docs.python.org/3/library/datetime.html#aware-and-naive-objects) consistently, e.g. `datetime.now(timezone.utc)` or `datetime.now(ZoneInfo("UTC"))`. utcnow returns naive datetime, which is misleading and error-prone (imho). – FObersteiner Jul 13 '23 at 08:56
  • 1
    @FObersteiner ```datetime.now(timezone.utc).time().tzinfo``` is None. It's possible to define ```time(tzinfo=ZoneInfo("UTC"))```, but not just time **now** UTC. – Mathieu B. Jul 13 '23 at 13:57
  • Right, although you can set a tzinfo for a `time` object, it doesn't have one if you detach it from a `datetime` object. Since time zone rules depend on *dates*, I don't see much point in having time without a date but with a time zone (UTC *might* be an exception). That's why I'd assume it was implemented like this in the Python standard library. – FObersteiner Jul 13 '23 at 15:53

0 Answers0