问题
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)
This give me the following error :
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'
I'd like to know how to write this correctly as I need to have the final date (after the minus 1, 2 or 3 days) in the following format : YYYYMMDD.
Thanks
回答1:
Do the subtraction in a separate statement:
from datetime import date, timedelta
dt = date.today() - timedelta(days=2)
Then convert it to a string in your format
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
回答2:
You can use datetime module. Make datetime instance and then add timedelta you want to:
dtm += datetime.timedelta(hours=2)
来源:https://stackoverflow.com/questions/58901554/syntax-to-use-to-make-minus-x-days-with-python-3-8