Python将datetime小时设置为特定时间 [英] Python set datetime hour to be a specific time

查看:1212
本文介绍了Python将datetime小时设置为特定时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将日期定为昨天晚上11.30。

I am trying to get the date to be yesterday at 11.30 PM.

这是我的代码:

    import datetime
    yesterday = datetime.date.today () - datetime.timedelta (days=1) 
    PERIOD=yesterday.strftime ('%Y-%m-%d') 
    new_period=PERIOD.replace(hour=23, minute=30)
    print new_period

但是我遇到此错误:

TypeError: replace() takes no keyword arguments

我们将不胜感激。

推荐答案

首先,将 datetime.date.today()更改为 datetime.datetime.today(),这样您就可以操纵一天中的时间。

First, change datetime.date.today() to datetime.datetime.today() so that you can manipulate the time of the day.

然后在将时间变为时调用 replace

Then call replace before turning the time into a string.

所以不是:

PERIOD=yesterday.strftime ('%Y-%m-%d') 
new_period=PERIOD.replace(hour=23, minute=30)

执行以下操作:

new_period=yesterday.replace(hour=23, minute=30).strftime('%Y-%m-%d')
print new_period

请注意,您将其转换为的字符串不显示有关小时或分钟的信息。如果您对此感兴趣,请在格式字符串中添加小时的%H 和分钟的信息%M

Also keep in mind that the string you're converting it to displays no information about the hour or minute. If you're interested in that, add %H for hour and %M for the minute information to your format string.

这篇关于Python将datetime小时设置为特定时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆