2010-05-18 2 views
30

나는 장고를 가르치기 위해 작은 피트니스 트래커를 연구 중이다. 시간이 지남에 따라 체중을 그래프로 나타내므로 Python Google Charts Wrapper를 사용하기로 결정했습니다. Google 차트를 사용하려면 날짜를 x 좌표로 변환해야합니다. 이렇게하기 위해 마지막 계량에서 첫 번째 계량을 뺀 다음 그 값을 사용하여 x 좌표를 계산하여 데이터 세트의 일 수를 가져 가고 싶습니다 (예를 들어, 결과로 100을 할 수 있고 x coord).Django/Python에서 두 날짜를 빼는 방법은 무엇입니까?

어쨌든, 장고 datetime 개체를 서로 빼고 지금까지 스택에서 Google과 여기에 모두 눈에 띄고 있습니다. 나는 PHP를 안다. 그러나 OO 프로그래밍에 대한 핸들을 결코 얻지 못했기 때문에 내 무지를 용서해 주길 바란다. 내 모델의 모습은 다음과 같습니다.

class Goal(models.Model): 
    goal_weight = models.DecimalField("Goal Weight", 
     max_digits=4, 
     decimal_places=1) 
    target_date = models.DateTimeField("Target Date to Reach Goal") 
    set_date = models.DateTimeField("When did you set your goal?") 
    comments = models.TextField(blank=True) 

    def __unicode__(self): 
     return unicode(self.goal_weight) 

class Weight(models.Model): 
    """ Weight at a given date and time. """ 

    goal = models.ForeignKey(Goal) 
    weight = models.DecimalField("Current Weight", 
     max_digits=4, 
     decimal_places=1) 
    weigh_date = models.DateTimeField("Date of Weigh-In") 
    comments = models.TextField(blank=True) 

    def __unicode__(self): 
     return unicode(self.weight) 

    def recorded_today(self): 
     return self.date.date() == datetime.date.today() 

보기를 진행하는 방법에 대한 아이디어가 있습니까? 정말 고마워!

답변

54

당신은 단지 datetime.timedelta 개체를 얻을 것이다, 직접 날짜를 뺄 수 있습니다

dt = weight_now.weight_date - weight_then.weight_date 

timedelta 객체는 일, 초 및 마이크로위한 필드가 있습니다. 거기에서 적절한 수학을 할 수 있습니다. 두 날짜 시간 (기본)하지 않고, 예를 들면, tzinfo 하나 하나를 다른 오프셋 인식을해야하는 경우에 작동하지 않습니다 뺀 것을

hours = dt.seconds/60/60 # Returns number of hours between dates 
weeks = dt.days/7    # number of weeks between dates 
+0

완벽하고 고마워요. 이것을 거의 그대로 사용했습니다. –

31

장고 datetime 개체는 그냥 일반 Python datetime objects입니다. 하나를 datetime에서 뺄 때 timedelta 개체를 얻습니다.

datetime에서 일정 시간을 빼려면 timedelta 개체를 뺄 필요가 있습니다. 예를 들어 :

>>> from datetime import datetime, timedelta 
>>> now = datetime.now() 
>>> print now 
2010-05-18 23:16:24.770533 
>>> this_time_yesterday = now - timedelta(hours=24) 
>>> print this_time_yesterday 
2010-05-17 23:16:24.770533 
>>> (now - this_time_yesterday).days 
1 
+0

이것은 훌륭합니다. 고마워요 ... 저는 문자열로 사고하는 데 많이 익숙해졌습니다. 두 개의 다른 객체를 뺀 객체가 생성 될 수 있다고 생각하지 않았습니다. –

3

참고 : 예를 들면.

+0

이 질문에 대한 답변이 아닙니다. 당신이 말한 것에 추가 할 것이 있으면 다른 대답에 대한 의견을 남기십시오. – FistOfFury

관련 문제