使用 Numpy 列印今天、昨天和明天的日期


在該專案中,我們將使用 Numpy 庫列印今天、昨天和明天的日期。

演算法

Step 1: Import the numpy library.
Step 2: find today's date using the datetime64() function.
Step 3: find yesterday's date by subtracting the output of timedelta64() function from the output of datetime64() function.
Step 4: Find yesterday's date by adding the output of timedelta64() function from the output of datetime64() function.

示例程式碼

import numpy as np

todays_date = np.datetime64('today', 'D')
print("Today's Date: ", todays_date)

yesterdays_date = np.datetime64('today', 'D') - np.timedelta64(1, 'D')
print("Yesterday's Date: ", yesterdays_date)

tomorrows_date = np.datetime64('today', 'D') + np.timedelta64(1, 'D')
print("Tomorrow's Date: ", tomorrows_date)

輸出

Today's Date: 2021-02-16
Yesterday's Date: 2021-02-15
Tomorrow's Date: 2021-02-17

說明

在 Numpy 中,有可支援 datetime 功能的資料型別。函式被命名為“datetime64”,因為“datetime”這個名稱已被 Python 中的一個庫用作名稱。

datetime64() 函式中的“D”引數用於以“日”為單位獲取日期。timedelta64() 函式用於表達時間差,例如,天、小時、分、秒。

更新日期: 2021 年 3 月 16 日

350 次瀏覽

開啟你的 職業 生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.