如何在 Python 中修改 datetime.datetime.hour?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36075197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:22:07  来源:igfitidea点击:

How to modify datetime.datetime.hour in Python?

pythondatetime

提问by Mars Lee

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

我想计算从现在到明天 12:00 之间的秒数。所以我需要得到明天 12:00 的datetime对象。

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 datetimeobject?

如何修改小时或如何获得明天 12:00 的datetime对象?

回答by Chris

Use the replacemethodto generate a new datetimeobject based on your existing one:

使用该replace方法datetime根据现有对象生成新对象:

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=Nonecan be specified to create a naive datetime from an aware datetime with no conversion of date and time data.

返回具有相同属性的日期时间,除了那些由指定的关键字参数赋予新值的属性。请注意,tzinfo=None可以指定从已知日期时间创建一个简单的日期时间,而无需转换日期和时间数据。

回答by Selcuk

Try this:

尝试这个:

tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0)