Summary of various pits in Python time processing

 TypeError: can't compare offset-naive and offset-aware datetimes

Combining Python and pydantic to handle various time zone issues

compare two times

It is necessary to pay attention to whether it contains time zone information. If one datetime contains time zone information and the other does not contain time zone information, an error will be reported!

 from datetime import datetime, timezone, date
from pydantic import BaseModel, Field


def get_utc_now_timestamp() -> datetime:
    return datetime.utcnow().replace(tzinfo=timezone.utc)


class Struct(BaseModel):
    create_at: datetime | None


s = Struct(create_at='1970-01-01 00:00:00')

assert s.create_at < get_utc_now_timestamp()

The error is as follows:

 Traceback (most recent call last):
  File "/Users/bot/Desktop/code/ideaboom/test_pydantic/001.py", line 29, in <module>
    assert s.create_at < get_utc_now_timestamp()
TypeError: can't compare offset-naive and offset-aware datetimes

reason:

  • offset-naive is a type without time zone,
  • And offset-aware is the time zone type

solution:

  • Bring time zone information.

    • You can use the replace method of datetime to add time zone information, such as replace(tzinfo=timezone.utc)
    • Or the original time string with time zone information, such as s = Struct(create_at='1970-01-01 00:00:00+08:00')
  • Or without time zone information, you can use the replace method of datetime to remove the time zone information, such as replace(tzinfo=None)

Reference article:

received a naive datetime while time zone support is active

python datetime offset-aware and offset-navie conversion

How to remove pytz timezone from datetime object?


universe_king
3.4k 声望680 粉丝