✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

Parsing axis values from relayoutData if type=date

I have a graph where I need to react to user interactions that change the x axis range, which is of type date. I use the relayoutData property as input to my callback to, which normally looks like this:

{"xaxis.range[0]": "2021-07-02 23:59:59.0888", "xaxis.range[1]": "2021-07-03 00:00:08.7182"}

So, to use this range in subsequent functions, I parsed it using strptime() from the datetime module and format %Y-%m-%d %H:%M:%S.%f.

However, testing this a bit I found that if I’m “lucky” enough to exactly land on a full second, the relayoutData may instead look like this:

{"xaxis.range[0]": "2021-07-02 23:59:58", "xaxis.range[1]": "2021-07-02 23:59:58.0007"}

Note how there are no milliseconds for xaxis.range[0]. If I land exactly on a new day it might even just be 2021-07-03.

This inconsistent formatting breaks strptime, of course, because the format doesn’t match anymore. What would be the best way to deal with this? Can I get around doing laborious parsing for each case?

For now, I do it like this:

PLOTLY_FMT = '%Y-%m-%d %H:%M:%S.%f'			# example: 2021-03-25 11:44:31.8968
PLOTLY_FMT_SEC = '%Y-%m-%d %H:%M:%S'		# example: 2021-03-25 11:44:31
PLOTLY_FMT_MIN = '%Y-%m-%d %H:%M'			# example: 2021-03-25 11:44
PLOTLY_FMT_DAY = '%Y-%m-%d'					# example: 2021-03-25

def plotly_to_datetime(plotly_string):
	fmts = [PLOTLY_FMT, PLOTLY_FMT_SEC, PLOTLY_FMT_MIN, PLOTLY_FMT_DAY]
	for fmt in fmts:
		try:
			return datetime.datetime.strptime(plotly_string, fmt)
		except ValueError:
			pass
	raise ValueError('Could not parse datetime from "{}"'.format(plotly_string))

IMO, this is way more complicated than it should be, and I don’t even know if I missed any possible format.