无论如何,在Python 3中是否检查小时以及是否在一小时后执行某项操作(如打印“它是下午)”?
这就是我已经完成的事情:
import time
import datetime
now = datetime.datetime.now().strftime("%d/%m/%y %H:%M:%S")
hour = datetime.hour().strftime("%H")
if (hour > 12):
print("it is the afternoon")
print(now)
如果我运行它,我会得到一个AttributeError。
答案 0 :(得分:2)
我建议如下:
import time
import datetime
now = datetime.datetime.now()
if (now.hour > 12):
print("it is the afternoon")
print(now.strftime("%d/%m/%y %H:%M:%S"))
答案 1 :(得分:1)
datetime
模块没有hour
方法,因此datetime.hour()
会崩溃。
也许你打算这样做:
now = datetime.datetime.now().strftime("%d/%m/%y %H:%M:%S")
hour = datetime.datetime.now().hour
答案 2 :(得分:0)
您可以直接从datetime.datetime
对象访问小时:
if (datetime.datetime.now().hour > 12)
print("Hello")
答案 3 :(得分:0)
这是因为您正在调用protected String put(String path, String parameters)
throws IOException {
HttpURLConnection connection = getConnection(path, "PUT", parameters);
OutputStreamWriter outputWriter = new OutputStreamWriter(
connection.getOutputStream());
outputWriter.write(parameters);
outputWriter.flush();
outputWriter.close();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String response = reader.readLine();
while(response != null){
response += reader.readLine();
}
reader.close();
return response;
}
private HttpURLConnection getConnection(String path, String method,String params) throws MalformedURLException, IOException,
ProtocolException {
URL url = new URL(this.api + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Length",
String.valueOf(params.length()));
return connection;
}
,其中datetime.hour()
是一个模块,而不是datetime
的对象。你可能意味着这样的事情:
datetime
但strftime将hour = datetime.datetime.now().strftime("%H")
返回str
(与另一个int
相当),因此您需要:
int
这绝对是一种矫枉过正。这是一个最简单的方法
hour = int(datetime.datetime.now().strftime("%H"))
或hour = datetime.datetime.now().hour
模块:
time