我正在構建一個使用 API 的股票研究程式,但我似乎無法弄清楚如何從日期時間中洗掉年、月和日。問題在于日期是用戶輸入,所以我嘗試使用 f 字串但它不起作用。腳本本身運行良好,只是我計劃將其自動化,因此它會自行轉移到 Excel 表,我希望有時間在 EST 中,因為這就是股票市場的運作方式。
df = pd.DataFrame({'h': [6.50, 6.63, 6.50, 6.50, 6.55, 6.55, 6.55, 6.57],
'date': [2022-04-22 08:46:00, 2022-04-22 09:14:00,
2022-04-22 09:41:00, 2022-04-22 09:45:00,
2022-04-22 11:54:00, 2022-04-22 11:57:00,
2022-04-22 12:06:00, 2022-04-22 13:00:00]
ticker = input('Ticker: ')
date = input('Date (YYYY-MM-DD): ')
data30 = requests.get(api_30).json()
data10 = requests.get(api_10).json()
data1 = requests.get(api_1).json()
data30['results']
data10['results']
data1['results']
df = pd.DataFrame(data1['results']) #Results grabbed from API
df['date'] = pd.to_datetime(df['t'], unit = 'ms')#To convert to datetime
df['date'] = pd.to_datetime(df['date'])#Label new column 'date'
pmhightime = df[(df['date'] > f'{date} 07:30:00') & (df['date'] < f'{date} 13:30:00')]#To display premarket hours only
pmhightime = pmhightime[['h','date']]#Change dataframe to only include 'h' being high and 'date'
pmhightime = pmhightime[pmhightime['h'] == pmhightime['h'].max()] #To find the row that has the highest value
pmhightime = pmhightime[['date']]#Change dataframe to only have date
print('Premarket High: ', pmhightime.to_string(index=False,header=False)) #To get rid of index and header
###Output /// for ticker I will put DOGZ and date 2022-04-22
Ticker: DOGZ
Date (YYYY-MM-DD): 2022-04-22
Premarket High: 2022-04-22 09:14:00
###The output I'd like to have
Ticker: DOGZ
Date (YYYY-MM-DD): 2022-04-22
Premarket High: 5:14:00 AM
uj5u.com熱心網友回復:
您當然可以使用 momentjs 庫,它為我們提供了各種各樣的功能,我們可以使用這些功能來滿足我們在特定用例中的需求。這是它的網站:https ://momentjs.com/
uj5u.com熱心網友回復:
您可以使用:
from datetime import datetime, timedelta, tzinfo
import pytz
def parseDate(date):
return datetime.strftime(pytz.timezone('US/Eastern').localize(date),'%H:%M')
datetime.strftime(date,'%H:%M') 將其格式化為 HH:MM
pytz.timezone('US/Eastern').localize(date) 本地化日期
uj5u.com熱心網友回復:
創建一個新列,僅將時間格式化為字串:
df["time"] = df["date"].dt.strftime("%I:%M %p")
>>> df
h date time
0 6.50 2022-04-22 08:46:00 08:46 AM
1 6.63 2022-04-22 09:14:00 09:14 AM
2 6.50 2022-04-22 09:41:00 09:41 AM
3 6.50 2022-04-22 09:45:00 09:45 AM
4 6.55 2022-04-22 11:54:00 11:54 AM
5 6.55 2022-04-22 11:57:00 11:57 AM
6 6.55 2022-04-22 12:06:00 12:06 PM
7 6.57 2022-04-22 13:00:00 01:00 PM
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/467765.html
