Sparky Sparky - 1 year ago 82
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)
end = date - dateutil.relativedelta.relativedelta(days=1)

Someone let me know the way to achieve this.

Answer Source

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 =
orig_end = + relativedelta.relativedelta(months=1)


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

mod_end = datetime(year=orig_end.year,
                   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)



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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download