Home > database >  What is the difference between Django timezone now and the built-in one?
What is the difference between Django timezone now and the built-in one?

Time:11-18

I've just noticed this:

>>> import datetime
>>> from django.utils import timezone

>>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).microseconds
999989

>>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).seconds
86399

>>> 24*60*60
86400

>>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).days
-1

>>> timezone.now()
datetime.datetime(2022, 11, 17, 13, 1, 36, 913132, tzinfo=<UTC>)

>>> datetime.datetime.now(tz=datetime.timezone.utc)
datetime.datetime(2022, 11, 17, 13, 1, 41, 913958, tzinfo=datetime.timezone.utc)

How do both options to get the current time with the UTC "timezone" differ? Why is the difference a positive number of seconds, but exactly negative one day?

Can I replace timezone.now() by datetime.datetime.now(tz=datetime.timezone.utc)?

CodePudding user response:

The second value in your subtraction is getting created a microsecond or so after the first value. So it's a later point in time. You're subtracting the later point in time from the earlier point in time. Yielding a negative delta:

>>> datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()
datetime.timedelta(days=-1, seconds=86399, microseconds=999981)

If you're only looking at the day or microsecond part of that, it looks like a huge difference. But this is simply the way a timedelta represents a fraction of a second in the past. It's minus one day plus 86399 seconds and 999981 ms. See Python timedelta object with negative values.

  • Related