How can I extract only the year from a date field (x_date_invoice) to a new computed odoo field for example x_jaar
4 Answers
Hello Pelingier,
Basic Function of Python,
strptime()
Description The method strptime() parses a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().
The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().
If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised.
Syntax
Following is the syntax for strptime() method:
time.strptime(string[, format])
Parameters
string -- This is the time in string format which would be parsed based on the given format.
format -- This is the directive which would be used to parse the given string.
strftime()
Description The method strftime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.
If t is not provided, the current time as returned by localtime() is used. format must be a string. An exception ValueError is raised if any field in t is outside of the allowed range.
Syntax
Following is the syntax for strftime() method:
time.strftime(format[, t])
Parameters
t -- This is the time in number of seconds to be formatted.
format -- This is the directive which would be used to format given time. The following directives can be embedded in the format string:
==========================================================================
Your Question Solution
The first import library is from datetime import datetime
after use all the functionality of the DateTime.
Try below code,
for record in self:
record['x_jaar'] = str(datetime.strptime(record['x_date_invoice'],"%d/%m/%Y %H:%M:%S").strftime("%Y"))
I hope my answer is helpful.
If any query so comments, please.