Skip to content

Instantly share code, notes, and snippets.

@SXHRYU
Created January 6, 2023 18:55
Show Gist options
  • Save SXHRYU/1e22d330a3b321a59fb9c02ea847412e to your computer and use it in GitHub Desktop.
Save SXHRYU/1e22d330a3b321a59fb9c02ea847412e to your computer and use it in GitHub Desktop.
Function that transforms string to `datetime.datetime` object with considerations for popular datetime formats. Meaning this function is format-agnostic and easily scalable (just add new formats).
def transform_to_datetime(date_string: str) -> datetime:
"""Normalises different datetimes and turns them into `datetime`
objects.
Needed in case time output from the site changes in the future.
Parameters
----------
date_string : str
Datetime presented in `str` format.
Returns
-------
datetime : datetime.datetime
Datetime presented in `datetime.datetime` format.
"""
# Needed because of different possible date fields.
popular_formats = [
"%Y-%m-%dT%H:%M:%S.%fZ", # -> "2022-08-11T21:09:01.123456Z"
"%Y-%m-%dT%H:%M:%SZ", # -> "2018-03-12T10:12:45Z"
"%b %d %Y at %I:%M%p", # -> "Jun 28 2018 at 7:40AM"
"%B %d, %Y, %H:%M:%S", # -> "September 18, 2017, 22:19:55"
"%a,%d/%m/%y,%I:%M%p", # -> "Sun,05/12/99,12:30PM"
"%a, %d %B, %Y", # -> "Mon, 21 March, 2015"
]
for format_ in popular_formats:
try:
datetime_obj: datetime = datetime.strptime(date_string, format_)
except ValueError:
continue
else:
break
return datetime_obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment