87

I want to calculate the seconds between now and tomorrow 12:00. So I need to get tomorrow 12:00 datetime object.

This is pseudo code:

today_time = datetime.datetime.now()
tomorrow = today_time + datetime.timedelta(days = 1)
tomorrow.hour = 12
result = (tomorrow-today_time).total_seconds()

But it will raise this error:

AttributeError: attribute 'hour' of 'datetime.datetime' objects is not writable

How can I modify the hour or how can I get a tomorrow 12:00 datetime object?

djromero
  • 19,551
  • 4
  • 71
  • 68
Mars Lee
  • 1,845
  • 5
  • 17
  • 37
  • You could take a look at [this answer](http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python) so you can convert **tomorrow 12:00** datetime to timestamp and then substract `time.time()` – pixis Mar 18 '16 at 02:41

2 Answers2

175

Use the replace method to generate a new datetime object based on your existing one:

tomorrow = tomorrow.replace(hour=12)

Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive datetime from an aware datetime with no conversion of date and time data.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
13

Try this:

tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0)
Selcuk
  • 57,004
  • 12
  • 102
  • 110