I would like to allow the user to specify the date format using a human readable format like 'YYYY-MM-DD'. But then I need to actually parse dates so I need the corresponding actual datetime format '%Y-%m-%d'. Is there a way go from the first to the second?
You can use a dictionary to convert human readable format or your custom format to strftime.
import datetime
def human_to_strftime(human_format):
format_mapping = {
'YYYY': '%Y',
'YY': '%y',
'MM': '%m',
'DD': '%d',
'HH': '%H',
'MI': '%M',
'SS': '%S',
'AM/PM': '%p'
}
strftime_format = human_format
for human, strftime in format_mapping.items():
strftime_format = strftime_format.replace(human, strftime)
return strftime_format
if __name__ == "__main__":
date = "2024-07-09"
date_format = "YYYY-MM-DD"
spec = human_to_strftime(date_format)
datetime_obj = datetime.datetime.strptime(date, spec)
print(datetime_obj)
Output:
2024-07-09 00:00:00