首页 > 解决方案 > 如何打印从今天起接下来的 3 个日期?

问题描述

我有一个代码可以告诉输入位置的天气。我想选择打印未来 3 天的天气,我需要向我的函数发送 3 个日期(带循环),每次不同的日期,如何从当天发送接下来 3 天的日期?

#This is my function
def weather(city, date): 

#This is the part where I send it from the main to the function:
city = 'Paris'
while(i < 4):
    i += 1
    weather(city.lower(), dd/mm/yyyy)# Here instead of "dd/mm/yyyy" I need to send every time the next date from today.

标签: pythondatedatetime

解决方案


生成日期范围的最简单方法是使用pandas.date_rangeas

import pandas as pd

dates = pd.date_range('2019-04-10', periods=3, freq='D')

for day in dates:
    weather(city, day)

或者你可以坚持在接下来的几天循环,你可以使用datetime.timedelta

from datetime import date, timedelta

one_day_delta = timedelta(1)
day = datetime.date(2019, 4, 19)
for i in range(3)
    day += one_day_delta
    weather(city, day)

推荐阅读