# convert date from string to datetime

**URL:** <https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557>\
**Category:** Forms & APIs\
**Created:** [November 22, 2023, 6:31pm UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557 "2023-11-22T18:31:45Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![ndagano](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ndagano/32/17253_2.png) [@ndagano](https://forum.djangoproject.com/u/ndagano)\
**Post date:** [November 22, 2023, 6:31pm UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/1 "2023-11-22T18:31:45Z")

</div>

i want to convert date stored on a server in string using expressions  
here the view:

```auto
class SubscribersListAPIView(ListAPIView):
    serializer_class = AbonesSerializer

    def get_queryset(self):
        start_date_param = self.request.query_params.get("start_date", None)
        end_date_param = self.request.query_params.get("end_date", None)

        start_date = None
        end_date = None

        if start_date_param:
            try:
                start_date = datetime.strptime(start_date_param, "%d/%m/%Y").date()
            except ValueError:
                pass

        if end_date_param:
            try:
                end_date = datetime.strptime(end_date_param, "%d/%m/%Y").date()
            except ValueError:
                pass

        queryset = Abones.objects.all()

        queryset = Abones.objects.annotate(
            date_as_datetime=ExpressionWrapper(F('date'), output_field=DateTimeField()
            )
        )

        if start_date_param and end_date_param:
            queryset = queryset.filter(date_as_datetime__range=(start_date, end_date))
        elif start_date_param:
            queryset = queryset.filter(date_as_datetime=start_date)
        elif end_date_param:
            queryset = queryset.filter(date_as_datetime=end_date)

        return queryset

```

but when i run the code they show me :  
AttributeError: ‘DateTimeField’ object has no attribute ‘model’  
where’s the problem??

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 22, 2023, 6:36pm UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/2 "2023-11-22T18:36:02Z")

</div>

Please post the full error message with the traceback, along with the model involved here.

Also, when you’re posting code or error messages, enclose the code (or error message) between lines of three backtick - ` characters. This means you’ll have a line of ```, then the code, then another line of ```. (I’ve taken the liberty of editing your original post for this. Please remember to do this in future posts.)

---

<div class="post-metadata">

**Author:** ![ndagano](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ndagano/32/17253_2.png) [@ndagano](https://forum.djangoproject.com/u/ndagano)\
**Post date:** [November 22, 2023, 6:44pm UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/3 "2023-11-22T18:44:00Z")

</div>

Here the model

```auto
class Abones(models.Model):
    idu = models.IntegerField(db_column='idU') # Field name made lowercase.
    nom = models.TextField()
    prenom = models.TextField()
    nom_pere = models.TextField()
    nom_mere = models.TextField()
    sexe = models.TextField()
    nationalite = models.TextField()
    date_naissance = models.TextField()
    identite = models.CharField(max_length=250)
    province_n = models.TextField()
    commune_n = models.TextField()
    zone_n = models.TextField()
    colline_n = models.TextField()
    residence = models.TextField()
    occupation = models.TextField(blank=True, null=True)
    recto = models.TextField()
    verso = models.TextField()
    photo = models.TextField()
    date = models.TextField()

    class Meta:
        managed = False
        db_table = 'abones'

```

This is the traceback:

```auto
Internal Server Error: /api/v1/subscribers-list
Traceback (most recent call last):
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view
return view_func(*args, **kwargs)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/views/generic/base.py", line 104, in view
return self.dispatch(request, *args, **kwargs)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
 File "/var/www/envs/onasoft/lib/python3.10/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
 File "/var/www/envs/onasoft/lib/python3.10/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/rest_framework/generics.py", line 199, in get
return self.list(request, *args, **kwargs)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/rest_framework/mixins.py", line 38, in list
queryset = self.filter_queryset(self.get_queryset())
File "/var/www/test/onasoft_test/onasoftadapter/apps/base/views.py", line 106, in get_queryset
queryset = queryset.filter(date_as_datetime=start_date)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/query.py", line 1436, in filter
return self._filter_or_exclude(False, args, kwargs)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/query.py", line 1454, in _filter_or_exclude
 clone._filter_or_exclude_inplace(negate, args, kwargs)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/query.py", line 1461, in _filter_or_exclude_inplace
 self._query.add_q(Q(*args, **kwargs))
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1534, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1565, in _add_q
child_clause, needed_inner = self.build_filter(
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1433, in build_filter
condition = self.build_lookup(lookups, reffed_expression, value)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1307, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/lookups.py", line 27, in __init__
self.rhs = self.get_prep_lookup()
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/lookups.py", line 341, in get_prep_lookup
return super().get_prep_lookup()
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/lookups.py", line 85, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/fields/ __init__.py", line 1585, in get_prep_value
value = super().get_prep_value(value)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/fields/ __init__.py", line 1464, in get_prep_value
return self.to_python(value)
File "/var/www/envs/onasoft/lib/python3.10/site-packages/django/db/models/fields/ __init__.py", line 1538, in to_python
% (self.model. __name__ , self.name, value),
 AttributeError: 'DateTimeField' object has no attribute 'model'

```

---

<div class="post-metadata">

**Author:** ![taeyoung1005](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/taeyoung1005/32/17285_2.png) [@taeyoung1005](https://forum.djangoproject.com/u/taeyoung1005)\
**Post date:** [November 23, 2023, 7:38am UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/4 "2023-11-23T07:38:05Z")

</div>

In my opinion, it seems like the date field of the model is declared as a TextField.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 23, 2023, 11:59am UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/6 "2023-11-23T11:59:16Z")

</div>

What is the data type of the original column in the database?

If it is a Varchar (or similar untyped text field), what are a couple of the values you’re seeing in it?

If it’s only a date, then the proper field type would be a DateField and not a DateTimeField.

---

<div class="post-metadata">

**Author:** ![ndagano](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ndagano/32/17253_2.png) [@ndagano](https://forum.djangoproject.com/u/ndagano)\
**Post date:** [November 23, 2023, 12:24pm UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/7 "2023-11-23T12:24:07Z")

</div>

it is a TextField  
There are some values that are like this

> ‘DD/MM/YYYY’

others like

> ‘DD/MM/YYYY %H:%M’

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 23, 2023, 12:57pm UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/8 "2023-11-23T12:57:05Z")

</div>

> [@ndagano](#):
>
> `date_as_datetime=ExpressionWrapper(F('date'), output_field=DateTimeField()`

You _may_ need to Cast that field as a date rather than just using the output\_field parameter.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 23, 2023, 1:31pm UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/10 "2023-11-23T13:31:26Z")

</div>

Well, that’s closer - at least it’s telling you that there’s _something_ in one of the rows that “doesn’t work”. You might want to examine the data more closely to see if there is any bad data in that field.

---

<div class="post-metadata">

**Author:** ![ndagano](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/ndagano/32/17253_2.png) [@ndagano](https://forum.djangoproject.com/u/ndagano)\
**Post date:** [November 23, 2023, 3:54pm UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/11 "2023-11-23T15:54:51Z")

</div>

I tested more solutions, it didn’t work

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 23, 2023, 4:03pm UTC](https://forum.djangoproject.com/t/convert-date-from-string-to-datetime/25557/12 "2023-11-23T16:03:34Z")

</div>

I would write a query or a script that would check that column in the database to see if there are rows where the value in that column is not of the required format. It only takes one row to be improper for the error to be thrown.
