75

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,431
  • 4
  • 69
  • 67
Mars Lee
  • 1,645
  • 3
  • 16
  • 35
  • 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

160

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.

Chris
  • 112,704
  • 77
  • 249
  • 231
11

Try this:

tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0)
Selcuk
  • 52,758
  • 11
  • 94
  • 99