Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Epoch time validation in marshmallow #1515

Open
vvksahoo opened this issue Feb 17, 2020 · 4 comments
Open

Epoch time validation in marshmallow #1515

vvksahoo opened this issue Feb 17, 2020 · 4 comments

Comments

@vvksahoo
Copy link

Hi,
I want to validate epoch time . Is there any way to do this using marshmallow. I will be getting this in request body . Dont know which format to be used .

 Time example: 1568783919
@lafrech
Copy link
Member

lafrech commented Feb 17, 2020

Related to #612 / #1003?

@vvksahoo
Copy link
Author

vvksahoo commented Feb 17, 2020

Hey @lafrech , i have gone through those link but seriously didnt get how to validate epoch time. if i will use start_at = fields.DateTime(required=True) then its giving "Not a valid datetime" for epoch time but for this '2012-09-13 02:22:5 format its working .

@lafrech
Copy link
Member

lafrech commented Feb 17, 2020

The issue and PR I pointed to are unfinished stuff. My point is that your question, if I understand it correctly, would be solved if the work on these was done and integrated. In other words, this might be a duplicate. Also, I didn't take the time to go through the conversations there again, but maybe you can find a few hints.

Right now marshmallow does not accept timestamps as datetimes. You may define custom field or a pre_load / post_dump processor.

@vvksahoo
Copy link
Author

    start_at = fields.DateTime(required=True)
    @pre_load
    def convert_epoch_time_to_datetime(self, data, **kwargs):
        try:
            data['start_at'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['start_at']))
        except (OSError, ValueError):
            raise ValidationError("start_at is invalid.")
 @post_load
    def convert_datetime_to_epoch_time(self, data, **kwargs):
        pattern = '%Y-%m-%d %H:%M:%S'
        start_at_in_str = data["start_at"].strftime(pattern)
        data["start_at"] = int(time.mktime(time.strptime(start_at_in_str, pattern)))
        return data

As of now , i am doing like this . But the problem here is , it wont give error msg like
"message": "{'start_at': ['Missing data for required field.']}" if you are not passing 'start_at' in request body .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants