2014-10-02 68 views
0

我有一個等於3:00的datetime.time字段。如何從python datetime.time字段獲取小時整數

如何從這個對象中得到3作爲整數?

我曾嘗試:

transaction_time = form.cleaned_data['transaction_time'] 
print transaction_time.hour 

我得到的錯誤:

'unicode' object has no attribute 'hour'

+0

您是否嘗試過首先獲取'datetime.time'? – 2014-10-02 03:26:05

回答

0

根據文檔:

If a Field has required=False and you pass clean() an empty value, then clean() will return a normalized empty value rather than raising ValidationError. For CharField, this will be a Unicode empty string. For other Field classes, it might be None. (This varies from field to field.)

https://docs.djangoproject.com/en/dev/ref/forms/fields/

所以當阿倫提到的,我做的字符串操作,以確定時間:

def set_hour_for_date(customer, hour_str, transaction_date): 
    meridian = hour_str[-2:] 
    hour = int(hour_str[:2]) 
    if meridian == 'PM': 
     hour = hour + 12 
    relative_time = customer.time_zone.localize(datetime(
                 transaction_date.year, 
                 transaction_date.month, 
                 transaction_date.day, 
                 hour, 
                 0, 
                 0, 
                 294757)) 

    return relative_time 
0

好像transaction_time是類型的Unicode。您可以使用字符串操作來獲取小時部分(transaction_time [0])或將它轉換爲datetime並獲取小時。

0

transaction_time是不是一個時間的對象,它的unicode,因此首先使用strptime將其首先轉換爲struct_time,然後獲取字段tm_hour。

from time import strptime 
t = strptime(form.cleaned_data['transaction_time'], '%H:%M') 

print t.tm_hour 
相關問題