Skip to content
Advertisement

Attempting to introduce dynamic variables causes a toordinal error

I’m trying to make the generation of charts a little bit more dynamic so other users can get a bit more value out of my code.

Currently, I do this (and variations of it) to produce a variety of charts:

date_min = datetime.strptime('25/05/22 08:00:00', '%d/%m/%y %H:%M:%S')
date_max = datetime.strptime('25/05/22 09:15:00', '%d/%m/%y %H:%M:%S')
plt.xlim(date_min,date_max)

And this works perfectly well, but involves people scrolling through the code to individually change the data.

What I’ve attempted to do is change it so that people define a target date (target_date), and the ranges of their time (time_min, time_max) at the beginning of the code, so all they have to do is run the code and all the charts are made.

I have attempted to add some dynamism by changing the date_min variable to this:

date_min = ''.join([datetime.strptime(target_date, '%d/%m/%y').strftime('%Y-%m-%d'), ' ', time_min])

However when I run the code, it trips up at:

plt.xlim(date_min,date_max)

And presents the following error message:

AttributeError: 'numpy.str_' object has no attribute 'toordinal'

This seems strange given the fact that printing the outputs of both date_min codes, they look the same with the same structure.

Does anyone know why I’m encountering this error?

For the record target_date is ’25/05/22′ (which is then converted to the right format), time_min is ’08:00:00′.

Thanks for any assistance.

Advertisement

Answer

Try this:

date_min = datetime.strptime(f"{target_date} {time_min}", "%d/%m/%y %H:%M:%S")
date_max = datetime.strptime(f"{target_date} {time_max}", "%d/%m/%y %H:%M:%S")

plt.xlim(date_min,date_max)

(assuming target_date, time_min and time_max are all strings)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement