question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Loading Datetime Objects

See original GitHub issue

Maybe this is not so much of an issue but a misunderstanding on my side, so I’d think the following pytest-style unit test should not raise a validation error, since a datetime.datetime instance should satisfy the property of being a a datetime already:

from marshmallow import Schema, fields
import datetime


class SomeSchema(Schema):
    element = fields.DateTime()


def test_datetime_loading_accepts_datetime_object():
    schema = SomeSchema(strict=True)
    res = schema.load({"element": datetime.datetime.now()})

I do however get a validation error marshmallow.exceptions.ValidationError: {'element': ['Not a valid datetime.']}

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:8
  • Comments:10 (1 by maintainers)

github_iconTop GitHub Comments

12reactions
JulienPalardcommented, Jul 28, 2017

I’m temporarily using this so deserialization accepts datetimes instances:

class MyDateTimeField(fields.DateTime):
    def _deserialize(self, value, attr, data):
        if isinstance(value, datetime):
            return value
        return super()._deserialize(value, attr, data)
6reactions
aklavercommented, Nov 23, 2017

If are serializing(dump) a DateTime field then you need to provide a datetime object:

import datetime
from marshmallow import Schema, fields
from dateutil import tz
class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()
    created_at = fields.DateTime()
usr_sch = UserSchema()
usr = {'name': "Adrian Klaver", 'email': "aklaver@example.com", 'created_at': datetime.datetime(2017, 11, 22, 9, 58, tzinfo=tz.tzutc())}
usr_sch.dump(usr)
MarshalResult(data={'name': 'Adrian Klaver', 'created_at': '2017-11-22T09:58:00+00:00', 'email': 'aklaver@example.com'}, errors={})

If you are going the other way deserializing(load) then you can use a string:

usr = {'name': "Adrian Klaver", 'email': "aklaver@example.com", 'created_at': '2017-11-22T09:58:00Z'}
usr_sch.load(usr)
UnmarshalResult(data={'name': 'Adrian Klaver', 'created_at': datetime.datetime(2017, 11, 22, 9, 58, tzinfo=tzutc()), 'email': 'aklaver@example.com'}, errors={})


Read more comments on GitHub >

github_iconTop Results From Across the Web

How to convert to a Python datetime object with JSON.loads?
If the schema is known, it should be pretty easy to make a function, which parses json and substitutes string representations with datetime....
Read more >
Using Python datetime to Work With Dates and Times
In this tutorial, you'll focus on using the Python datetime module. The main focus of datetime is to make it less complicated to...
Read more >
Python datetime (With Examples) - Programiz
One of the classes defined in the datetime module is datetime class. We then used now() method to create a datetime object containing...
Read more >
Ultimate Guide to Datetime! Python date and time objects for ...
Hi everyone! today we will talk about the Datetime module, which helps us load and manipulate date and time data in Python.
Read more >
datetime — Basic date and time types — Python 3.11.1 ...
A timedelta object represents a duration, the difference between two dates or times. class datetime.timedelta(days= ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found