1 import datetime
 2 
 3 import pytz
 4 from django.apps import AppConfig
 5 from django.db.models.fields import DateTimeField
 6 from django.utils.dateparse import parse_date
 7 from django.core.exceptions import ValidationError
 8 
 9 default_app_config = 'patch.PatchConfig'
10 
11 
12 def patch():
13     def get_db_prep_value(self, value, connection, prepared=False):
14         if isinstance(value, str):
15             if not value:
16                 value = None
17             elif not parse_date(value):
18                 try:
19                     value = datetime.datetime.fromtimestamp(int(value)).replace(tzinfo=pytz.UTC)
20                 except:
21                     raise ValidationError(
22                         self.error_messages['invalid'],
23                         code='invalid',
24                         params={'value': value},
25                     )
26         if not prepared:
27             value = self.get_prep_value(value)
28         return connection.ops.adapt_datetimefield_value(value)
29 
30     DateTimeField.get_db_prep_value = get_db_prep_value
31 
32 
33 class PatchConfig(AppConfig):
34     name = 'patch'
35 
36     def ready(self):
37         patch()