I am trying the run below lines of code in a loop and want to define the timedelta as a variable as it will keep varying.
START_TIME = f"{datetime.datetime.now() - timedelta(int('%d')):%d/%m/%Y 00:00}" % COUNT
END_TIME = f"{datetime.datetime.now() - timedelta(int('%d')):%d/%m/%Y 23:59}" % COUNT
However, this is failing with below error:
ValueError: invalid literal for int() with base 10: '%d'
I am trying to get start and end time of the day for past few days and do some action over it. I tried few other ways too but did not work.
This happens because string formatting (solving the expressions in {}
) is executed before the printf-style substitution (string % object
).
Although it seems to be a bit less readable, it might be better to rearrange your code - calculate START_TIME
, END_TIME
first and then convert everything to strings.
If you need to have them in one line each, you could also use brackets and call the string.format()
method explicitly to ensure it's done last. The following very generall example will work:
("{%d}" % 0).format('Hello')
Output:
Hello
However, given your examples this will still not be very readable.