[Python Basics] How to get yesterday’s date

1 Get yesterday’s date

When obtaining data from some securities data statistics websites, the latest data is often from the previous day. When encountering similar websites, we often need to obtain yesterday's date.
To get yesterday’s date using Python, you can use Python’s built-in datetime module. The specific steps are as follows:

# 1.导入datetime模块
import datetime
# 2.获取当前日期
today = datetime.date.today()
# 3.计算昨天的日期
yesterday = today - datetime.timedelta(days=1)
# 4.打印昨天的日期
print("Yesterday was:", yesterday)

The output is as follows:

Yesterday was: 2023-08-11

In step 3 above, we used the timedelta function to calculate the day before the current date and stored the result in the yesterday variable.

2 Get the date before the specified date

Another function of the timedelta method is that we can specify a date and then calculate the day of the month before it.
For example, the following code demonstrates how to calculate the date one day before August 13, 2023:

import datetime   # 导包

date = datetime.date(2023, 8, 13)  # 创建对象
yesterday = date - datetime.timedelta(days=1)  # 计算日期

print("Yesterday was:", yesterday)

The output is as follows:

Yesterday was: 2023-08-12

In this example, we create a datetime object that represents August 13, 2023. The previous day's date was then calculated using the timedelta function and the result was stored in the yesterday variable. Finally, yesterday's date is printed.

3 Get the date n days before the specified date

We can also get earlier dates in a similar way by just changing the value of timedelta.days to the desired number of days.
For example, if you want to get the date 5 days ago, you can change the days parameter to 5.

import datetime   # 导包

date = datetime.date(2023, 8, 13)  # 创建对象
yesterday = date - datetime.timedelta(days=5)  # 计算日期

print("Yesterday was:", yesterday)

The output is as follows:

Yesterday was: 2023-08-08

The above is a complete guide to using Python to get yesterday's date. I hope it will be helpful to you.

Guess you like

Origin blog.csdn.net/weixin_43498642/article/details/132254837