Data conversions for Django model fields Datetime and Decimal

Common problem with date and time

 You will get error messages like 

ValueError: unconverted data remains: 

ValueError: time data '30/09/2022' does not match format '%dd/%mm/%YYYY'

transaction.settlement_date = datetime.strptime(row[5], '%d/%m/%y') # 30/09/2022

 

Solution of it 

 

from dateutil import parser 

datetime_obj = parser.parse('2018-02-06T13:12:18.1278015Z')
print datetime_obj
 

Decimal number

 You will get error messages like 
 
django.core.exceptions.ValidationError: ['“-2900,00” value must be a decimal number.'] 
 
Because in Dutch you have come numbers and it working with a point. 
 
.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
 
In most of cases you want to change locale
 
import locale
locale.setlocale(locale.LC_ALL, 'nl_NL')

position = 123.45678999 print(f'{position:.4n}') # output: 123,4 (not quite what we wanted!)
print(f'{round(position, 4):n}') # output: 123,4567 (that's it!)

But here I would leave in English notation because different data from different languages will come in. 

Just do a replace!

So, you can use somthing like this.. 

 

def convert_nl_decimal(self, value):
        value = value.strip()
        if (len(value) > 0) and (value.find(',') != -1):
            return Decimal(value.replace(',', '.'))
        else:
            return Decimal(0.0)



 
 
 
 

 

 

 

Comments