簡體   English   中英

將日期從 yfinance Timestamp 寫入 influxdb 並查詢日期 - 時區支持

[英]write date from yfinance Timestamp to influxdb and query the date - timezone support

大家好,新年快樂!

我正在嘗試將日期/時間數據寫入 influxdb 並將數據查詢到 dataframe。

當我寫數據日期時間看起來像這樣......

ticker= 'AAPL'
import yfinance as yf
df = yf.Ticker('AAPL').history(period="1d").index[0]
print(df)

output:
Timestamp('2023-01-05 00:00:00-0500', tz='America/New_York')

...當我將數據查詢到 dataframe 並打印出來時,我得到了這個:

df['_time']

output:
0   2023-01-05 05:00:00+00:00
Name: _time, dtype: datetime64[ns, tzutc()]

我需要做什么才能在 influxdb 中正確寫入時間?

請參閱下面的完整代碼:

########## WRITE ##########

    import yfinance as yf
    import influxdb_client
    from influxdb_client.client.write_api import SYNCHRONOUS, PointSettings


    token = "my-token"
    org = "my-org"
    url = "my-url"
    bucket = "stocks_us"
    retention_policy = "autogen"
    
    client = influxdb_client.InfluxDBClient(url=url, token=token, org=org)
    write_api = client.write_api(write_options=SYNCHRONOUS)

   df = yf.Ticker('AAPL').history(period="1d")

   with client:
    """
    Ingest DataFrame with default tags
    """
    point_settings = PointSettings(**{"ticker": ticker})
    
    write_api = client.write_api(write_options=SYNCHRONOUS, 
                                 point_settings=point_settings)
    write_api.write(bucket=bucket, 
                    org= "dev", 
                    record=df, 
                    data_frame_measurement_name="stock_daily_df")

    client.close()

    print(df)

########## QUERY ##########

import influxdb_client 

token = "my-token"
org = "my-org"
url = "my-url"
bucket = "stocks_us"
retention_policy = "autogen"

client = influxdb_client.InfluxDBClient(url=url, token=token, org=org)

query_api = client.query_api()
measurement= "stock_daily_df"

with client:
    
    """
    Querying ingested data
    """
    query = 'from(bucket:"{}")' \
            ' |> range(start: 0, stop: now())' \
            ' |> filter(fn: (r) => r._measurement == "{}")' \
            ' |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")' \
            ' |> filter(fn: (r) => r["ticker"] == "AAPL")'\
            ' |> limit(n:10, offset: 0)'.format(bucket, measurement)
            
    df = query_api.query_data_frame(query=query)

    print(df)
    

任何幫助表示贊賞

Flux 將在UTC中完成所有工作,這是一個簡單的線性時鍾,並將其留給用戶來確定顯示。 因此,為了保持時間戳的一致性,我們應該在插入數據之前將時間戳轉換為UTC,並在完成查詢后將數據結果轉換回相應的時間戳。

1.在yfinance庫中將時間戳轉換成UTC:

dt.replace(tzinfo=timezone.utc)

2.將 UTC 時間戳轉換為本地時間戳:

import "timezone"

option location = timezone.location(name: "America/New_York")

在此處查看更多詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM