Skip to content

Instantly share code, notes, and snippets.

@DrDougPhD
Created November 4, 2016 03:29
Show Gist options
  • Save DrDougPhD/658523267f0b7088a4e281f7249bb27d to your computer and use it in GitHub Desktop.
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!
#!/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