Computer >> Máy Tính >  >> Lập trình >> Python

In ngày hôm nay, hôm qua và ngày mai bằng Numpy

Trong chương trình này, chúng tôi sẽ in ngày hôm nay, ngày hôm qua và ngày mai bằng thư viện numpy.

Thuật toán

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.

Mã mẫu

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)

Đầu ra

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

Giải thích

Trong numpy, có các kiểu dữ liệu hỗ trợ chức năng datetime. Tên 'datetime64' được đặt cho hàm vì tên 'datetime' đã được sử dụng bởi một thư viện trong Python.

Tham số 'D' trong hàm datetime64 () để lấy ngày trong đơn vị 'days'. Hàm timedelta64 () được sử dụng để thể hiện sự khác biệt về thời gian, chẳng hạn như ngày, giờ, phút, giây.