Generic routine to convert arbitrary formated dates as string into datetime objects.
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
""" | |
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