2016-03-18 24 views
8

Tôi muốn tính số giây từ giờ đến ngày mai 12:00. Vì vậy, tôi cần phải có được ngày mai 12:00 datetime đối tượng.Cách sửa đổi datetime.datetime.hour bằng Python?

Đây là mã giả:

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

Nhưng nó sẽ nâng cao được lỗi này:

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

Làm thế nào tôi có thể thay đổi giờ hoặc làm thế nào tôi có thể có được một ngày mai 12:00 datetime đối tượng?

+0

Bạn có thể có một cái nhìn tại [câu trả lời này] (http : //stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python) để bạn có thể chuyển đổi ** ngày mai 12: 00 ** datetime thành dấu thời gian và sau đó trừ đi 'time.time () ' – pixis

Trả lời

18

Sử dụng replace method để tạo ra một đối tượng mới datetime dựa trên của bạn hiện có:

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

Hãy thử điều này:

tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0) 
Các vấn đề liên quan