Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify datetime.datetime.hour in Python?

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?

like image 607
Mars Lee Avatar asked Mar 18 '16 02:03

Mars Lee


People also ask

How do you declare an hour in Python?

Yes, just do date = datetime. strptime('26 Sep 2012', '%d %b %Y'). replace(hour=11, minute=59) .

How do you edit datetime?

You can't change a DateTime value - it's immutable. However, you can change the variable to have a new value. The easiest way of doing that to change just the time is to create a TimeSpan with the relevant time, and use the DateTime.


2 Answers

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.

like image 143
Chris Avatar answered Sep 27 '22 21:09

Chris


Try this:

tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0) 
like image 28
Selcuk Avatar answered Sep 27 '22 19:09

Selcuk