Python Django:如何从时间发布中获得时差?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16016002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django: How to get a time difference from the time post?
提问by dorafmon
Say I have a class in model
说我在模型中有一个类
class Post(models.Model):
time_posted = models.DateTimeField(auto_now_add=True, blank=True)
def get_time_diff(self):
timediff = timediff = datetime.datetime.now() - self.time_posted
print timediff # this line is never executed
return timediff
I defined a get_time_diff to get the time difference from the time when the Post is posted up to now, according to the document, the DateTimeField should be able to be converted to datetime automatically, is that correct? Why the print statement is never being run? How can you extract the time difference?
我定义了一个get_time_diff来获取从Post发布到现在的时差,根据文档,DateTimeField应该可以自动转换为datetime,对吗?为什么打印语句永远不会运行?你如何提取时差?
Beside, if you get a time difference, is there an easy way to convert the time difference to an integer, like the number of seconds of the total time.
此外,如果您得到时差,是否有一种简单的方法可以将时差转换为整数,例如总时间的秒数。
采纳答案by Martijn Pieters
Your code is already working; a datetime.timedeltaobjectis returned.
您的代码已经在运行;返回一个datetime.timedelta对象。
To get the total number of secondsinstead, you need to call the .total_seconds()methodon the resulting timedelta:
要获得总数秒相反,你需要调用.total_seconds()方法上产生的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 floatvalue, including microseconds.
.total_seconds()返回一个float值,包括微秒。
Note that you need to use a timezone awaredatetimeobject, since the Django DateTimeFieldhandles timezone aware datetimeobjects as well. See Django Timezones documentation.
请注意,您需要使用时区感知datetime对象,因为 Django 也DateTimeField处理时区感知datetime对象。请参阅Django 时区文档。
Demonstration of .total_seconds()(with naive datetimeobjects, but the principles are the same):
演示.total_seconds()(用幼稚的datetime对象,但原理是一样的):
>>> 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 .tzinfoattribute 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.
因为这两个对象都知道时区(有一个.tzinfo不是的属性None),所以它们之间的计算会处理时区,并且在考虑到任一对象的时区时,从另一个中减去一个将做正确的事情。
回答by Rohan
Your code
你的代码
timediff = datetime.datetime.now() - self.pub_date
should work to get the time difference. However, this returns timedeltaobject. To get difference in seconds you use .secondsattribute
应该工作以获得时差。但是,这会返回timedelta对象。要以秒为单位获得差异,请使用.seconds属性
timediff = datetime.datetime.now() - self.pub_date
timediff.seconds # difference in seconds.
回答by Wolph
回答by therealadrain
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!
以防万一你想把这个过程放在你的 Django 信号中。这是对我有用的那个。希望这可以帮助!
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;

