Created
November 4, 2016 03:29
-
-
Save DrDougPhD/658523267f0b7088a4e281f7249bb27d to your computer and use it in GitHub Desktop.
Convert a raw string into an appropriate datatype by using trial and error!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from dateutil.parser import parse | |
def convert(value): | |
""" | |
Be aware that this script is likely very incomplete. For instance, I don't even consider float! | |
""" | |
if value.lower() == "true": | |
return True | |
if value.lower() == "false": | |
return False | |
if value == "": | |
return None | |
# attempt to convert to integer | |
try: | |
return int(value) | |
except: | |
pass | |
# attempt to convert to datetime | |
try: | |
return parse(value) | |
except: | |
pass | |
# after all failures, just return a string | |
return str(value) | |
if __name__ == "__main__": | |
print(convert("2")) | |
print(convert("ab3")) | |
print(convert("2011-03-18T16:14:00Z")) | |
print(convert("FALSE")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment