Last active
January 16, 2020 09:49
-
-
Save martimors/77b52ff173b74256dbcaf79b2ba5d0f2 to your computer and use it in GitHub Desktop.
Parse a datetime string in Python
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
from datetime import datetime | |
class DateTimeParseError(Exception): | |
pass | |
def parse_datetime(date): | |
""" | |
Checks if a date has a valid format ISO8601 formatting and returns | |
a parsed datetime object with the correct timezone if applicable. | |
Args: | |
date (str): Date formatted as a string | |
Returns: | |
Date (datetime.datetime): Date object | |
""" | |
try: | |
date_object = datetime.strptime(date, "%Y-%m-%dT%H:%M:%SZ") | |
return date_object | |
except (ValueError, TypeError): | |
pass | |
try: | |
date_object = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ") | |
return date_object | |
except (ValueError, TypeError): | |
pass | |
try: | |
date_object = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%f") | |
return date_object | |
except (ValueError, TypeError): | |
pass | |
raise DateTimeParseError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment