[英]how to get hour integer from python datetime.time field
I have a datetime.time field that is equal to 3:00. 我有一个等于3:00的datetime.time字段。
How can I get 3 as an integer from this object? 如何从该对象获取3作为整数?
I have tried: 我努力了:
transaction_time = form.cleaned_data['transaction_time']
print transaction_time.hour
I get the error: 我得到错误:
'unicode' object has no attribute 'hour'
“ unicode”对象没有属性“ hour”
Seems like transaction_time is of type unicode. 好像transaction_time是unicode类型。 You can use string manipulation to get the hour part(transaction_time[0]) or typecast it to datetime and get hour.
您可以使用字符串操作获取小时部分(transaction_time [0])或将其类型转换为日期时间并获取小时。
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.
如果Field的required = False,并且您将clean()传递为空值,则clean()将返回规范化的空值,而不是引发ValidationError。 For CharField, this will be a Unicode empty string.
对于CharField,这将是Unicode空字符串。 For other Field classes, it might be None.
对于其他Field类,它可能为None。 (This varies from field to field.)
(这因字段而异。)
https://docs.djangoproject.com/en/dev/ref/forms/fields/ https://docs.djangoproject.com/en/dev/ref/forms/fields/
So as Arun mentioned, I did string manipulation to determine the time: 因此,正如Arun所述,我进行了字符串操作来确定时间:
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. 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.