Reputation: 241
In my current project I have some duplicated code and I am looking for a possibility to remove it. I have a boolean called forward
. If it's true, I want to add days to a datetime, if not I want to subtract days:
if forward:
day = today + datetime.timedelta(days=3)
else:
day = today - datetime.timedelta(days=3)
Is there any possibility to do that in less than these 4 lines?
Upvotes: 0
Views: 75
Reputation: 169378
Assuming it's not statically 3
, multiply with -1 or +1 depending on direction?
n_days = 10
day = today + datetime.timedelta(days=(n_days * (1 if forward else -1)))
Upvotes: 3