Skip to content

Instantly share code, notes, and snippets.

@plainspooky
Last active August 15, 2022 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plainspooky/d8cb781af96a6e3f011eb89caf30ec45 to your computer and use it in GitHub Desktop.
Save plainspooky/d8cb781af96a6e3f011eb89caf30ec45 to your computer and use it in GitHub Desktop.
Generic routine to convert arbitrary formated dates as string into datetime objects.
"""
Convert an arbitrary string to a DateTime object
"""
from datetime import datetime
IGNORE_KEY = "no"
DATE_KEYS = (
"day",
"month",
"year",
"hour",
"minute",
"second",
)
DATE_SEP = "-"
TIME_SEP = ":"
SEP = " "
def convert_to_dt(date: str, **args) -> datetime:
"""Converts a date/time string in an arbitrary format to a `datetime`
object.
Receive the string as `date`, optionaly, can receive `key` containing
the desired fields (`DATE_KEYS` by default), `sep` as the separator
between date and time, `date_sep` as date separator and `time_sep` as
time separator."""
sep, keys, date_sep, time_sep = [
args.get(k, v)
for k, v in (
("sep", SEP),
("keys", DATE_KEYS),
("dt_sep", DATE_SEP),
("tm_sep", TIME_SEP),
)
]
date_part, time_part = date.split(sep)
date_dict = {
k: int(v)
for k, v in zip(
keys, date_part.split(date_sep) + time_part.split(time_sep)
)
if not k == IGNORE_KEY
}
return datetime(**date_dict)
if __name__ == "__main__":
# date in DD/MM/AAAA HH:MM:SS format
SAMPLE_1 = "01/05/1973 11:15:00"
print(convert_to_dt(SAMPLE_1, dt_sep="/"))
# date in YYYY-MM-DD,HH:MM:SS format (ignoring last two fields)
SAMPLE_2 = "2019-04-30,12:34:56"
print(
convert_to_dt(
SAMPLE_2,
keys=("year", "month", "day", "hour", IGNORE_KEY, IGNORE_KEY),
sep=",",
dt_sep="-",
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment