Search code examples
djangoformsdatetimedjango-rest-framework

timedata does not match format even though they are identical


Issue: ValueError: time data '2024-05-26 18:00' does not match format 'YYYY-MM-DD HH:mm'

I use DRF to fetch POST for api/reservations/. But Django complained that str cannot be passed to DateTimeField. So I tried to format str into proper datetime. But even though the string and format are exactly identical, various method still complain about something unknown by me.

Code:

def create(self, validated_data):
  validated_data.update({
    'reservation_time': datetime.datetime.strptime(validated_data.get('reservation_time'), 'YYYY-MM-DD HH:mm').date()
  })
  return self.Meta.model(**validated_data)

I was trying to change datetime format via JS to "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." (point a the end is a part of format and not a typo) and do so in Python, no progress. Tried django.utils.dateparse.parse_date as well, as datetime.datetime.strptime. parse_date returned None, meaning, something is wrong with format and strptime raises ValueError above. What am I missing?


Solution

  • The format works with percentages, see the full format specs [python-doc]:

    def create(self, validated_data):
        validated_data.update(
            {
                'reservation_time': datetime.datetime.strptime(
                    validated_data.get('reservation_time'), '%Y-%m-%d %H:%M'
                ).date()
            }
        )
        return self.Meta.model(**validated_data)