2016-12-01 71 views
-1
from django.utils import timezone 


good = Goods.objects.get(id=num) 
now = timezone.now() 

print(good.create_time) 
print(now) 

如何比較這些是否是一天。如何在Django中比較兩個日期時間?

2016-12-01 10:21:32.746505+00:00 
2016-12-01 10:24:08.906268+00:00 
+0

將它們轉換爲字符串,然後使用comaprison運營商'><=' –

+3

你想知道他們是相同的日曆日或彼此24小時內? – roganjosh

+0

嘗試將問題標題複製到Google。 – Sayse

回答

2

使用timedelta

d1 = datetime(year=2016, month=12, day=1) 
d2 = datetime(year=2016, month=12, day=2) 

abs(d2 - d1) < timedelta(days=1) 

或者,如果你只是想當天進行比較,可以從.day屬性訪問:

d1.day # 1 
d2.day # 2 
1

你必須create a new timedelta與指定的時間量:

d > timedelta(days=1) 

還是這個稍微更完整的腳本將幫助說明一下:

import datetime 
from time import sleep 

start = datetime.datetime.now() 
sleep(3) 
stop = datetime.datetime.now() 

elapsed = stop - start 

if elapsed > datetime.timedelta(days=1): 
    print "Slept for > 1 days" 

if elapsed > datetime.timedelta(seconds=1): 
    print "Slept for > 1 second" 

輸出:

Slept for > 1 second