Sparky Sparky - 7 months ago 13
Python Question

Customizing time of the datetime object in python

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.

Answer

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