iCodeLikeImDrunk
iCodeLikeImDrunk

Reputation: 17806

Can't subtract datetime and timestamp in django?

I have a field timestamp = models.DateTimeField(auto_now_add=True) in the db. I want to find the difference between that timestamp and datetime.now().

When I tried datetime.now() - timestamp, I get the error:

can't subtract offset-naive and offset-aware datetimes

How do I fix this?

Upvotes: 11

Views: 8478

Answers (2)

ePi272314
ePi272314

Reputation: 13437

Holá
The short answer is:

tz_info = your_timezone_aware_variable.tzinfo

diff = datetime.datetime.now(tz_info) - your_timezone_aware_variable:

You must add the timezone info to your now() time.
But you must add the same timezone of the variable, thats why I first read the tzinfo attribute.

Upvotes: 0

Cianan Sims
Cianan Sims

Reputation: 3429

This error refers to how times are stored by python. According to the python documentation:

There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment.

The django documentation also states that:

When time zone support is disabled, Django uses naive datetime objects in local time. This is simple and sufficient for many use cases. In this mode, to obtain the current time, you would write:

import datetime
now = datetime.datetime.now() 

When time zone support is enabled, Django uses time-zone-aware datetime objects. If your code creates datetime objects, they should be aware too. In this mode, the example above becomes:

import datetime
from django.utils.timezone import utc
now = datetime.datetime.utcnow().replace(tzinfo=utc)

You should determine whether or not you want timezone awareness in your site and then adjust your stored times accordingly. To convert an aware dt to naive you can use the pytz module and do this:

naive_dt = aware_dt.replace(tzinfo=None)

This works because all python datetimes have an optional timezone attribute, tzinfo, which can be used to store information on the dt's offset from UTC time.

Upvotes: 22

Related Questions