如何将日期时间应用于存储在字典中的数据框中的列?

How to apply datetime to a column within a dataframe that is stored in a dictionary?

我已经设法创建了一个数据帧字典,但我不确定如何将时间列转换为日期时间,因为我总是会出错。我选择了数据:

for k, v in rates.items():

    print(v['time'])

我是否需要将字典改回数据框然后执行此操作?代码具有日期时间对象,但我似乎无法在此处完成。我以为它只会转换它们..

rates['time']=pd.to_datetime(rates['time'], unit='s')
                           
# -*- coding: utf-8 -*-
"""
Created on Mon May 25 00:34:03 2020

@author: DanPc
"""

import pytz
import pandas as pd
import MetaTrader5 as mt5
import time
from datetime import datetime
from threading import Timer
import talib
import numpy as np
import matplotlib as plt
from multiprocessing import Process
import sys

server_name = "ICMarkets-MT5"
server_num = 
password = ""



#------------------------------------------------------------------------------
def actualtime():
    # datetime object containing current date and time
    now = datetime.now()
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    #print("date and time =", dt_string)
    return str(dt_string)
#------------------------------------------------------------------------------
def sync_60sec(op):

    info_time_new = datetime.strptime(str(actualtime()), '%d/%m/%Y %H:%M:%S')
    waiting_time = 60 - info_time_new.second

    t = Timer(waiting_time, op)
    t.start()

    print(actualtime)
#------------------------------------------------------------------------------
def program(symbol):
    if not mt5.initialize(login=server_num, server=server_name, password=password):
        print("initialize() failed, error code =",mt5.last_error())
        quit()


# set time zone to UTC
timezone = pytz.timezone("Etc/UTC")
# create 'datetime' object in UTC time zone to avoid the implementation of a local time zone offset
utc_from = datetime(2020, 1, 10, tzinfo=timezone)
    
   # Create currency watchlist for which correlation matrix is to be plotted

sym = ["GBPUSD","USDJPY","USDCHF","AUDUSD","GBPJPY"]


# Copying data to dataframe

utc_from = datetime.now()
for i in sym:
     rates = {i:pd.DataFrame(mt5.copy_rates_from(i, mt5.TIMEFRAME_M1, utc_from ,  10), 
             columns=['time', 'open', 'low', 'high', 'close', 'tick_volume', 'spread', 'real_volume']).drop(['tick_volume','spread','real_volume'], axis=1)for i in sym}

for k, v in rates.items():
    
    print(v['time'])


    
if not mt5.initialize():
        print("initialize() failed, error code =",mt5.last_error())
        quit()         
    
   
  
    
mt5.shutdown()


  
if not mt5.initialize():
        print("initialize() failed, error code =",mt5.last_error())
        quit()

         
# starting mt5
if not mt5.initialize(login=server_num, server=server_name, password=password):
    print("initialize() failed, error code =",mt5.last_error())
    quit()          
#------------------------------------------------------------------------------
#                   S T A R T I N G   M T 5 
#------------------------------------------------------------------------------
authorized=mt5.login(server_num, password=password)
if authorized:
    account_info=mt5.account_info()
    if account_info!=None:       
        account_info_dict = mt5.account_info()._asdict()
        df=pd.DataFrame(list(account_info_dict.items()),columns=['property','value'])
        print("account_info() as dataframe:")
        print(df)
else:
    print(mt5.last_error)

mt5.shutdown()
#------------------------------------------------------------------------------

def trading_bot():
    symbol_1 = 'EURUSD'
    
    while True:
        program(symbol_1)
        time.sleep(59.8) # it depends on your computer and ping

sync_60sec(trading_bot)



是的,您需要将 rates 转换为具有列 time 的数据框。

我认为您在这里混淆了字典和数据框。我想混淆是因为数据框是一个 列字典 ,对吗?

所以为了澄清起见,字典是一组对 (k, v),其中 v 可以是从数字到结构化对象的任何内容。在您的情况下,除非您的 v 是 v[time] 有效的对象,例如它是一个键为 time 的字典,你会遇到问题。

仅供参考,数据框字典是一个非常复杂的数据结构:)。

如果每个值都是一个 DF,那么你做的是正确的。但是当你进行日期时间转换时,似乎你是在整个字典 rates 上做的,这是错误的。您需要对每个值执行此操作。因此,对值使用 for 循环,或 map 将转换应用于每个值。