0

For the billing purpose, I have code which will generate necessary data as needed.

But there is one issue I am currently facing with the time gap.I have idea of fixing the same by adding the default time value.

To be precise consider the following date time object value.

2016-03-22 05:36:07.703078
2016-04-21 05:36:07.703078

One is the value of begin date and whereas another one is the value of end date.

Now I need to set the begin date as "2016-03-22 00:00:00" and end date as "2016-04-21 23:59:59".

Here it is a code, I have used for creation of begin date and end date.

    # begin date and end date set
    begin = date - dateutil.relativedelta.relativedelta(months=1)
    print(begin)
    print(type(begin))
    end = date - dateutil.relativedelta.relativedelta(days=1)
    print(end)

Someone let me know the way to achieve this.

1 Answer 1

1

Python's datetime objects are immutable, ie date_obj.hour = 23 results with
AttributeError: attribute 'hour' of 'datetime.datetime' objects is not writable.

Instead we need to create a new datetime object. Consider this as a guide:

from datetime import datetime
from dateutil import relativedelta

orig_start = datetime.now()
orig_end = datetime.now() + relativedelta.relativedelta(months=1)

print(orig_start)
print(orig_end)

mod_start = datetime(year=orig_start.year,
                     month=orig_start.month,
                     day=orig_start.day,
                     hour=0, minute=0, second=0)

mod_end = datetime(year=orig_end.year,
                   month=orig_end.month,
                   day=orig_end.day,
                   hour=23, minute=59, second=59)

# or even better as suggested in the comments:
mod_end = orig_end.replace(hour=23, minute=59, second=59, microsecond=0)

print(mod_start)
print(mod_end)

outputs:

2016-04-22 16:11:08.171845
2016-05-22 16:11:08.171845
2016-04-22 00:00:00
2016-05-22 23:59:59
Sign up to request clarification or add additional context in comments.

3 Comments

perhaps cleaner to use the date time object's replace method, like d.replace(hour=0, minute=0, second=0, microsecond=0)
@bgporter Agreed, wasn't aware of that one.
@bgporter Could you guys please have a look of this : stackoverflow.com/questions/36763849/…

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.