Python 将日期时间小时设置为特定时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23642676/
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
Python set datetime hour to be a specific time
提问by jxn
I am trying to get the date to be yesterday at 11.30 PM.
我试图将日期设为昨天晚上 11.30。
Here is my code:
这是我的代码:
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
however i am getting this error:
但是我收到此错误:
TypeError: replace() takes no keyword arguments
any help would be appreciated.
任何帮助,将不胜感激。
采纳答案by huu
First, change datetime.date.today()to datetime.datetime.today()so that you can manipulate the time of the day.
首先,更改datetime.date.today()为datetime.datetime.today()以便您可以操纵一天中的时间。
Then call replacebefore turning the time into a string.
然后replace在将时间变成字符串之前调用。
So instead of:
所以而不是:
PERIOD=yesterday.strftime ('%Y-%m-%d')
new_period=PERIOD.replace(hour=23, minute=30)
Do this:
做这个:
new_period=yesterday.replace(hour=23, minute=30).strftime('%Y-%m-%d')
print new_period
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 %Hfor hour and %Mfor the minute information to your format string.
另请记住,您将其转换为的字符串不显示有关小时或分钟的信息。如果您对此感兴趣,请将%H小时和%M分钟信息添加到格式字符串中。
回答by andmart
Is this what you want?
这是你想要的吗?
from datetime import datetime
yesterday = datetime(2014, 5, 12, 23, 30)
print yesterday
Edited
已编辑
from datetime import datetime
import calendar
diff = 60 * 60 * 24
yesterday = datetime(*datetime.fromtimestamp(calendar.timegm(datetime.today().utctimetuple()) - diff).utctimetuple()[:3], hour=23, minute=30)
print yesterday
回答by Yuriy Arhipov
You can use datetime.combine(date, time, tzinfo=self.tzinfo)
您可以使用 datetime.combine(date, time, tzinfo=self.tzinfo)
import datetime
yesterday = datetime.date.today () - datetime.timedelta (days=1)
t = datetime.time(hour=23, minute=30)
print(datetime.datetime.combine(yesterday, t))

