簡體   English   中英

如何導入時間的特定部分,例如 Python 中的小時或分鍾?

[英]How do I import specific parts of the time, e.g. hours or minutes in Python?

我曾經在 Python 2 中有一個程序(我現在使用的是版本 3),它可以找到時間的特定部分,例如小時或分鍾。 可悲的是,我弄丟了正在使用的 Raspberry Pi。 我知道它涉及from datetime import datetime命令,但我不知道如何應用它。 網絡上似乎沒有任何關於此的任何地方。

我不記得它是如何工作的,但它可能是這樣的:

from datetime import datetime

hour = datetime.hour()
print("The current hour is " + hour + "!")

這將返回以下內容

>>>The current hour is 13!

您應該首先查看Python 的官方文檔,因為它列出了標准庫的所有功能。 一個簡單的谷歌搜索“python 3 datetime hour”就會得到你所需要的。

from datetime import datetime

hour = datetime.now().hour
print("The current hour is " + hour + "!")

看看這里

from datetime import datetime
now = datetime.now()

如果您然后嘗試打印(現在),您將擁有整個日期時間戳...

2016-01-13 20:14:48.836659

您可以通過以下方式單獨訪問它們:

now.hour
now.minute
now.second
...

您可能正在尋找:

In [29]: hour = datetime.now().hour
In [30]: print('the current hour is {}!'.format(hour))
the current hour is 20!

datetime.now()是完整的當前日期和時間,具有單獨的日、月、小時等屬性:

In [31]: datetime.now()
Out[31]: datetime.datetime(2016, 1, 13, 20, 0, 57, 648969)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM