Skip to content

Instantly share code, notes, and snippets.

@Menziess
Created June 15, 2024 15:31
Show Gist options
  • Save Menziess/2324638c790413386fe22ce1f85b34d7 to your computer and use it in GitHub Desktop.
Save Menziess/2324638c790413386fe22ce1f85b34d7 to your computer and use it in GitHub Desktop.
from datetime import datetime as dt, timezone
from re import match
from toolz.curried import curry
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
DATE_FORMAT = '%Y-%m-%d'
@curry
def string_to_datetime(format: str, timestamp: str) -> dt:
"""Curried function converting string to datetime."""
return dt.strptime(timestamp, format).replace(tzinfo=timezone.utc)
def dict_replace_regex_match_values(
d: dict,
regex: str = r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z',
func=string_to_datetime(DATETIME_FORMAT)
) -> dict:
"""Apply function to values that match regex."""
return {
k: (
func(v) if isinstance(v, str) and match(regex, v)
else dict_replace_regex_match_values(v, regex, func)
if isinstance(v, dict)
else [dict_replace_regex_match_values(_, regex, func) for _ in v]
if isinstance(v, list)
else tuple(dict_replace_regex_match_values(
_, regex, func
) for _ in v)
if isinstance(v, tuple)
else v
)
for k, v in d.items()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment