python - 使用 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。
谢谢
解决方案
在单独的语句中进行减法:
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
推荐阅读
- java - 无法加载 ApplicationContext Java 测试
- python - 尽管代码在 Python 中运行无错误,但运行时错误
- node.js - 如何让雪包在包内查找子路径
- c# - 无法在 C# 应用程序中检测到硬盘驱动器
- regex - 匹配与前一组相同的重复次数
- rust - 使用 cc crate,我如何强制使用特定的编译器?
- python - 在没有 conda 的 Windows 上 pip install fbprophet
- python - 用空格分隔的整数字符串对列表进行排序
- .net - RavenDb - 安全模式下的 CertificateNameMismatchException
- php - 将 docker-compose 转换为 Kubernetes 用于 nginx 和 php-fpm 容器