Skip to main content
 首页 » 编程设计

python之在只需要更改日期的情况下创建日期时间对象的更好方法是什么

2025年05月04日15开发

  • 我需要从不同的 datetime 对象创建一个 datetime,其中 day 需要更改。

  • 我还需要保留 tzinfo。

我就是这样

day = 16 
today = datetime.today() 
 
print 'today:', today 
 
from_date = datetime(today.year, today.month, day, today.hour, 
                     today.minute, today.second, today.microsecond, 
                     today.tzinfo) 

当我运行这个时,我得到

today: 2013-06-01 09:19:37.138404 
from_date: 2013-06-16 09:19:37.138404 

我想知道是否有更好的 pythonic 方法来做到这一点

请您参考如下方法:

您使用 datetime.replace() method在实例上:

from_date = today.replace(day=day) 

Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.