I have a datetime.time field that is equal to 3:00.
How can I get 3 as an integer from this object?
I have tried:
transaction_time = form.cleaned_data['transaction_time']
print transaction_time.hour
I get the error:
'unicode' object has no attribute 'hour'
Seems like transaction_time is of type unicode. You can use string manipulation to get the hour part(transaction_time[0]) or typecast it to datetime and get hour.
According to the docs:
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/
So as Arun mentioned, I did string manipulation to determine the time:
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
transaction_time is not a time object, it's unicode, so convert it first to a struct_time using strptime , then get the field tm_hour.
from time import strptime
t = strptime(form.cleaned_data['transaction_time'], '%H:%M')
print t.tm_hour
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.