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

Validating if Strings follow datetime object syntax. #260

Open
AaronShah2 opened this issue Jun 24, 2021 · 0 comments
Open

Validating if Strings follow datetime object syntax. #260

AaronShah2 opened this issue Jun 24, 2021 · 0 comments

Comments

@AaronShah2
Copy link

I was using this class to validate datetime objects in various queries. However, due to various circumstances, the datetime objects inside these queries were stored as strings. I created this method below to solve this issue:

from datetime import datetime
from django.utils.dateparse import parse_datetime

def convert_to_datetime(data: Any) -> Any:
    """Recursive Helper function that converts datetime objects to
    proper type

    Returns:
        Object: data dictionary that has had its datetime values
        converted
    """
    if isinstance(data, dict):
        for k, v in data.items():
            data[k] = convert_to_datetime(v)
    elif isinstance(data, list):
        for i,e in enumerate(data):
            data[i] = convert_to_datetime(e)
    elif isinstance(data, str):
        try:
            dateObj = parse_datetime(data)
            if dateObj is None:
                return data
            else:
                return dateObj
        except ValueError:
            pass
    return data
struct = {
            "startDate": type(datetime(2018, 1, 22, 3, 20, 6)),
            "endDate": type(datetime(2020, 4, 20, 2, 4, 8))
}

data = {
            "startDate": '2016-04-20T01:07:16Z',
            "endDate": '2020-11-12T04:20:04Z'
}
convertedData = convert_to_datetime(data)
Schema(struct).validate(convertedData) 

I would be happy to contribute this code to the repository if a fix for this issue does not exist.

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

No branches or pull requests

1 participant