如何组合Django日期字段和时间字段

2024-06-25 05:39:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了以下查询:

start_date = DateField()
strt_time = TimeField()
obj=model.objects.annotate(
                datetimeobj=ExpressionWrapper(F('start_date') + F('strt_time'), output_field=DateTimeField()

它给出了以下错误:

AttributeError: 'decimal.Decimal' object has no attribute 'tzinfo'

我也尝试过这个解决方案:

data=model.objects.annotate(datetime=datetime.combine('start_date','start_time'))

它给出了错误:

TypeError: combine() argument 1 must be datetime.date, not str

谢谢


Tags: objdatetimedatemodelobjectstime错误start
1条回答
网友
1楼 · 发布于 2024-06-25 05:39:46

问题出在代码data=model.objects.annotate(datetime=datetime.combine('start_date','start_time'))中,因为您正在将字符串传递给combine()方法,该方法需要日期和时间

要合并日期和时间,请使用语法为

datetime.combine(date, time)

因此,您必须按照以下步骤操作:

data=model.objects.annotate(datetime=datetime.combine(start_date,start_time))

相关问题 更多 >