0

i'm trying to convert a string with this form "2019-07-17T16:00:50.282203+01:30" to timezone format so i can update models.DateTimeField field.

models.py:

from django.utils import timezone

class task(models.Model):
       title = models.CharField(max_length=100)
       create_date = models.DateTimeField(default=timezone.now)
       .
       .
       .

request will be like this:

{
    "title": "editeddd task",
    "create_date" : "2019-07-17T16:00:50.282203+01:30"

}

being stuck in converting UTC part.

view.py:

.
.
.
create_date = datetime.strptime(self.request.data['expiration_date'], '%Y-%m-%dT%H:%M:%S.%f%z')
.
.

‍‍the error is for %z part. it can converting "2019-07-17T16:00:50.282203+0130" but not "2019-07-17T16:00:50.282203+01:30" (notice to : in UTC part)

mehdi
  • 1,100
  • 1
  • 11
  • 27

2 Answers2

1

Being strict while sending and tolerant while receiving, you should do a little string mangling on that create_date string before passing it on to strptime.

My suggestions is to work with a regular expression, or to have look at rreplace - How to replace the last occurrence of an expression in a string? to get rid of that last :.

Hope this helps!

Bart Van Loon
  • 1,430
  • 8
  • 18
1

As you are referencing request.data, it looks as though you are using Django REST Framework. In that case the most straightforward way is to use DRF's serializers to parse / validate the incoming data.

from rest_framework import serializers

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ('title', 'create_date')

If you just want to retrieve the validated data you can do:

>>> serializer = TaskSerializer(data=request.data)
>>> serializer.is_valid(raise_exception=True)
>>> serializer.validated_data
OrderedDict([('title', 'editeddd task'), ('create_date', datetime.datetime(2019, 7, 17, 14, 30, 50, 282203, tzinfo=<UTC>))])

Or if you want to save a new task:

task = serializer.save()

It's important to validate all incoming data and validating each field manually by reaching into request.POST or request.data tends to be error prone. DRF's serializers (or Django's forms) have a lot of pre-built logic and make the task significantly easier and safer.

Jeremy
  • 1,308
  • 10
  • 11