The pit of python datime-received a naive datetime while time zone support is active

When you use Django to insert some time-type data, you are likely to encounter the above error. Why?

from datetime import datetime

print(datetime.utcnow())

Because the confusing utcnow does not carry time zone information, and Django will perform time zone verification on data of type datetime

utcnow with utc time zone information?

To ask another question, you can ask:
If you let the python datetime type bring time zone information, such as utc time zone information

Need to use the following code

datetime.utcnow().replace(tzinfo=timezone.utc)

Let's see the difference in output:

from datetime import datetime, timezone

a = datetime.utcnow()
print(a, type(a))

a = datetime.utcnow().replace(tzinfo=timezone.utc)
print(a, type(a))

The output is:

2021-11-01 05:18:11.165279 <class 'datetime.datetime'>
2021-11-01 05:18:11.165811+00:00 <class 'datetime.datetime'>

See +00:00 the back? This is the time zone information.

This timeinfo information is stored in the datetime class

@property
def tzinfo(self):
    """timezone info object"""
    return self._tzinfo

If you are using python to deal with some time zone related content, you can take a look at the following content:
A time helper tool commonly used
mac mysql modify the default time zone to utc


universe_king
3.4k 声望678 粉丝