0

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?

3
  • day = today + datetime.timedelta(days=3 if forward else -3) . # timedelta works with negative numbers as well which is same as using -timedelta Commented Jun 26, 2020 at 9:52
  • (operator.add if forward else operator.sub)(today, datetime.timedelta(days=3))… But is that really more readable…?! Commented Jun 26, 2020 at 9:53
  • 1
    There are shorter ways, but none are clearer than what you already have. Commented Jun 26, 2020 at 9:56

1 Answer 1

3

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)))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.