Type Datetime can be datetime.datetime or str

The fields of type Datetime are partly available as datetime.datetime object and partly as str, depending on where the functions were called from.

I run into this problem all the time. Usually I need the datetime.datetime object for further processing.

Current solution is to convert every time if necessary:

def get_datetime(datetime_to_convert):
	if isinstance(datetime_to_convert, datetime.datetime):
		return datetime_to_convert
	else:
		return datetime.datetime.strptime(datetime_to_convert, '%Y-%m-%d %H:%M:%S')

But I can’t imagine that this could be the right solution for this issue. What’s the right way?

To answer my own question:

The Frappe Framework already provides such helper functions. In this specific case its frappe.utils.data.get_datetime().

2 Likes