import datetime
class my_datetime(datetime.datetime):
@staticmethod
def utcnow():
return datetime.datetime.now(tz=datetime.timezone.utc).replace(tzinfo=None)
datetime.datetime = my_datetime
And then in your codebase make sure you import my_patches whenever you use datetime. E.g.: import my_patches
import datetime
print(datetime.datetime.utcnow())Don’t monkeypatch Python, m’kay?
from my_patches import monkey
monkey.patch_datetime_utcnow()
I wouldn't do it as a side-effect of an import. Down that path lies Ruby. :-)But if you're not writing gevent or pytest, you should probably avoid it. It's much better to explicitly import or create the modified version of the code inside your own namespace, like:
from helpers import my_datetime_utcnow
or import datetime as dt
def my_datetime_utcnow(): return dt.datetime.whatever...
If you're going out of your way to patch the `datetime` namespace in such a way that other modules importing it get your patched version, it's quite likely that all hell will break loose when you least expect it.It should never be acceptable to break working software for anything else than critical security problems.
Why prefer to work with naive UTC datetimes, rather than explicit UTC datetimes?
What's wrong with plain `datetime.datetime.now(datetime.UTC)`?
user_over_30d_old = user.created_at < datetime.datetime.utcnow() - datetime.timedelta(30)
But in the future, I would need to do:
user_over_30d_old = user.created_at.replace(tzinfo=datetime.UTC) < datetime.datetime.now(datetime.UTC) - datetime.timedelta(30)
Which isn't any better than the solution I proposed above, of removing UTC from the now() datetime. Alternatively, I could modify my DAL code to promote datetimes from naive to timezoned in the database at the edge of the python layer, but that would have a lot of knock-on effects in things like isoformat() now appending timezone information, which has caused issues in other broken APIs that I use.