Odoo插件升级时日期字段报错:ValueError时间格式不匹配
Hey there! Let's get that date field error sorted out. The ValueError: time data '%Y-%m-%d' does not match format '2020-10-09 00:00:0' is happening because your fields.Date field is getting a value that doesn't match what it expects.
What's Wrong with Your Current Code?
Your line:
date = fields.Date(string='Date',default=datetime.now())
has two key issues:
datetime.now()returns a datetime object (with hours, minutes, seconds), butfields.Dateonly accepts a date object or a string in%Y-%m-%dformat. Odoo tries to parse this datetime value into a date, which causes the format mismatch error.- You're assigning
datetime.now()directly as the default, not using a lambda. This means the default date will be fixed to the time when your Odoo module loads, not the current date when a user opens the form.
Correct Solutions
Here are two proper ways to set the default date for your fields.Date field:
Option 1: Use Odoo's Built-in fields.date Utility (Recommended)
Odoo provides a helper for date fields that handles everything correctly:
from odoo import models, fields class PartnerImportUpdate(models.TransientModel): _name = "partner.import.update" import_update = fields.Selection(selection=[('import','Import'),('update','Update')], string="Import Operations", default="import") date = fields.Date(string='Date', default=lambda self: fields.date.today()) one_time_import = fields.Boolean(string='First Time Import',help="If you have large no. of customers on your woocommerce site then enable this It will import product page by page",default = False)
fields.date.today()returns a date object (without time components) that perfectly matchesfields.Daterequirements.- Using
lambda self: ...ensures the default date is calculated when the form is opened, not when the module loads.
Option 2: Manually Convert Datetime to Date
If you prefer using Python's datetime module directly:
from odoo import models, fields from datetime import datetime class PartnerImportUpdate(models.TransientModel): _name = "partner.import.update" import_update = fields.Selection(selection=[('import','Import'),('update','Update')], string="Import Operations", default="import") date = fields.Date(string='Date', default=lambda self: datetime.now().date()) one_time_import = fields.Boolean(string='First Time Import',help="If you have large no. of customers on your woocommerce site then enable this It will import product page by page",default = False)
datetime.now().date()extracts just the date part from the current datetime, giving you a valid date object.
Quick Note on Your Commented Code
Your commented line:
# date = fields.Date("Date",default=lambda *args: datetime.strftime('%Y-%m-%d %H:%M:%S'))
was also incorrect because strftime() needs to be called on a datetime object (like datetime.now().strftime('%Y-%m-%d')), and fields.Date doesn't need the time part anyway. Stick to the solutions above for clean, Odoo-compliant code.
内容的提问来源于stack exchange,提问作者Yagami

