首页 > 解决方案 > 使用 Python 3.8 生成“减 x 天”的语法?

问题描述

    import pandas as pd
    import requests
    from bs4 import BeautifulSoup
    import time
    import datetime
    from datetime import date, timedelta

    # MM/DD/YYYY : time.strftime("%m/%d/%Y")
    # YYYYMMDD : time.strftime('%Y%m%d')

if datetime.datetime.now().isoweekday() == 1 : # If today is a Monday -> some dates must be minus 3 days to take the previous Friday's data

    url_DAX = 'https://www.eurexchange.com/exchange-en/market-data/statistics/market-statistics-online/100!onlineStats?viewType=4&productGroupId=13394&productId=34642&cp=&month=&year=&busDate=' + str(time.strftime('%Y%m%d') - timedelta(days=3))   #Should be minus 3 days
    df = pd.read_html(url_DAX)[0]
    df.to_csv('results_DAX_' + str(time.strftime('%Y%m%d')) + '.csv') 
    print(df)

这给了我以下错误:

 url_DAX = 'https://www.eurexchange.com/exchange-en/market-data/statistics/market-statistics-online/100!onlineStats?viewType=4&productGroupId=13394&productId=34642&cp=&month=&year=&busDate=' + str(time.strftime('%Y%m%d') - timedelta(days=2))  # Should be minus 2 days
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

我想知道如何正确地写这个,因为我需要有以下格式的最终​​日期(在负 1、2 或 3 天之后):YYYYMMDD。

谢谢

标签: pythonpython-3.xpython-datetime

解决方案


在单独的语句中进行减法:

from datetime import date, timedelta
dt = date.today() - timedelta(days=2)

然后将其转换为您格式的字符串

busdate =  dt.strftime('%Y%m%d')
url_DAX = 'https://www.eurexchange.com/exchange-en/market-data/statistics/market-statistics-online/100!onlineStats?viewType=4&............&busDate=' + busdate

推荐阅读