41π
Your code is already working; a datetime.timedelta
object is returned.
To get the total number of seconds instead, you need to call the .total_seconds()
method on the resulting timedelta
:
from django.utils.timezone import utc
def get_time_diff(self):
if self.time_posted:
now = datetime.datetime.utcnow().replace(tzinfo=utc)
timediff = now - self.time_posted
return timediff.total_seconds()
.total_seconds()
returns a float
value, including microseconds.
Note that you need to use a timezone aware datetime
object, since the Django DateTimeField
handles timezone aware datetime
objects as well. See Django Timezones documentation.
Demonstration of .total_seconds()
(with naive datetime
objects, but the principles are the same):
>>> import datetime
>>> time_posted = datetime.datetime(2013, 3, 31, 12, 55, 10)
>>> timediff = datetime.datetime.now() - time_posted
>>> timediff.total_seconds()
1304529.299168
Because both objects are timezone aware (have a .tzinfo
attribute that is not None
), calculations between them take care of timezones and subtracting one from the other will do the right thing when it comes to taking into account the timezones of either object.
12π
Assuming you are doing this within a template, you can also use the timesince template tag.
For example:
{{ blog_date|timesince:comment_date }}
- [Django]-Django model CharField: max_length does not work?
- [Django]-How to encode UTF8 filename for HTTP headers? (Python, Django)
- [Django]-Django and domain driven design
1π
Your code
timediff = datetime.datetime.now() - self.pub_date
should work to get the time difference. However, this returns timedelta
object. To get difference in seconds you use .seconds
attribute
timediff = datetime.datetime.now() - self.pub_date
timediff.seconds # difference in seconds.
- [Django]-Should server IP address be in ALLOWED_HOSTS django setting?
- [Django]-How do I mock a django signal handler?
- [Django]-Generating a Random Hex Color in Python
0π
Just in case you want to put this process in you Django signals. Hereβs the one that is working for me. Hope this helps!
from django.db.models.signals import pre_save
from django.dispatch import receiver
from .models import YourModel
from datetime import datetime
@receiver(pre_save, sender = YourModel)
def beforeSave(sender, instance, **kwargs):
date_format = "%H:%M:%S"
# Getting the instances in your model.
time_start = str(instance.time_start)
time_end = str(instance.time_end)
# Now to get the time difference.
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)
# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;
- [Django]-Is there a HAML implementation for use with Python and Django
- [Django]-PyCharm: DJANGO_SETTINGS_MODULE is undefined
- [Django]-Django Admin Show Image from Imagefield
0π
Simply we can add the custom property to calculate the time difference with the help @property
decorator in that model.
from django.utils import timezone
class Post(models.Model):
time_posted = models.DateTimeField(auto_now_add=True, blank=True)
content = models.TextField()
@property
def time_diff(self):
return timezone.now() - self.time_posted
time_diff
will return object of datetime.timedelta
post = Post.objects.get(pk=1) # Post model object
# time diff in seconds.
post.time_diff.seconds
>>> 652
# time diff in days.
post.time_diff.days
>>> 0
Already answered above nicely by Martijn Pieters, just adding @property
, and django.utils.timezone
to calculate the difference with respective timezone from settings.py
- [Django]-How to return generated file download with Django REST Framework?
- [Django]-Why did Django 1.9 replace tuples () with lists [] in settings and URLs?
- [Django]-Going from twitter date to Python datetime date