macos 在 python 中使用 datetime.replace() 更改小时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2213682/
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-10-21 06:44:24  来源:igfitidea点击:

Changing the hour with datetime.replace() in python

pythonmacosdatetime

提问by cit

Given that foo is a valid datetime object in python,

鉴于 foo 是 python 中的有效日期时间对象,

One can change the hour represented in a datestamp (foo) by doing something something like:

可以通过执行以下操作来更改日期戳 (foo) 中表示的小时:

foo2 = foo.replace( hour=5 ) 

Rather then replacing the hour with a particular value ( as is done above )..is it possible to increment the time in foo by say, 5 hours ? Something along the lines of:

而不是用特定值替换小时(如上所述)。是否可以将 foo 中的时间增加 5 小时?类似的东西:

foo2 = foo.replace( hour += 5 ) 

Which I know is not correct...but maybe that explains better what I am aiming to do...

我知道这是不正确的......但也许这更好地解释了我的目标......

I am limited to using python 2.5.1 ( the version on OS X 10.5.x) .. and am not able to add any modules such as pyTZ

我只能使用 python 2.5.1(OS X 10.5.x 上的版本)..并且无法添加任何模块,例如 pyTZ

回答by balpha

That's what timedeltais for:

timedelta就是为了:

>>> import datetime
>>> d = datetime.datetime(2010, 12, 25, 18, 25)
>>> d + datetime.timedelta(hours = 8)
datetime.datetime(2010, 12, 26, 2, 25)