marshmallow icon indicating copy to clipboard operation
marshmallow copied to clipboard

Epoch time validation in marshmallow

Open vvksahoo opened this issue 4 years ago • 4 comments

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

vvksahoo avatar Feb 17 '20 06:02 vvksahoo

Related to #612 / #1003?

lafrech avatar Feb 17 '20 07:02 lafrech

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 .

vvksahoo avatar Feb 17 '20 09:02 vvksahoo

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.

lafrech avatar Feb 17 '20 09:02 lafrech

    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 .

vvksahoo avatar Feb 25 '20 05:02 vvksahoo