2016-03-18 13 views
8

Chcę obliczyć sekundy od teraz do jutra 12:00. Więc muszę dostać jutro 12:00 datetime obiektu.Jak zmodyfikować datetime.datetime.hour w Pythonie?

To pseudo kod:

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

Ale to podniesie ten błąd:

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

Jak mogę zmodyfikować godzinę lub jak mogę dostać jutro 12:00 datetime obiekt?

+0

Można przyjrzeć się [tej odpowiedzi] (http : //stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python), dzięki czemu możesz konwertować ** jutro 12: 00 ** datetime na znacznik czasu, a następnie odjąć 'time.time () ' – pixis

Odpowiedz

18

Użyj replace method wygenerować nowy datetime obiektu na podstawie istniejących 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.

2

Spróbuj tego:

tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0) 
Powiązane problemy