Python字典中的时间键

2024-04-24 19:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV导出,以15分钟为间隔列出日期/时间。你知道吗

时间在导出中显示为以下示例:2019-09-04T02:15:00Z

导入文件后,我将时间(HH:MM:SS)分隔到一个新列中。我想添加一个新的列,为字典中每15分钟的间隔分配一个文本字符串(“ON”或“RTH”)。你知道吗

在Excel中这样做很简单,但是我正在尝试学习如何通过Python。每次运行此代码时,新列都是空的(没有错误消息)。我认为字典的键使用时间有问题。有人能告诉我我错过了什么吗?你知道吗

import pandas as pd

# file export from TradingView

df = pd.read_csv(file, sep=',')
df = df.rename(columns={'time': 'Date', 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close'})


df["Date"] = pd.to_datetime(df["Date"])

df["Time"] = df["Date"].dt.time

# a shortened version of the dictionary for illustration

time_dictionary = {'02:15:00': 'ON', '02:30:00': 'ON', '11:00:00': 'RTH'}

# new column to assign the text strings

df['Session'] = df['Time'].map(time_dictionary)

Tags: csvthetodfdate间隔dictionary字典
3条回答

我认为这是因为df['Time']与Time\u字典中的键的数据类型不同。你可能在比较字符串和时间。你知道吗

您可能需要首先使用以下内容将其更改为string


df["Time"] = df["Date"].dt.time

df["Time"] = df["Time"].strftime('%r')

您正在使用

df["Time"] = df["Date"].dt.time

哪个

returns numpy array of datetime.time (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.time.html)

使用

df["Time"] = df["Date"].dt.strftime('%H:%M:%S')

相反,它返回格式化字符串(https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.strftime.html)。你知道吗

完整代码:

import pandas as pd

# file export from TradingView

df = pd.read_csv(file, sep=',')
df = df.rename(columns={'time': 'Date', 'open': 'Open', 'high': 'High', 'low': 'Low', 'close': 'Close'})


df["Date"] = pd.to_datetime(df["Date"])

df["Time"] = df["Date"].dt.strftime('%H:%M:%S')

# a shortened version of the dictionary for illustration

time_dictionary = {'02:15:00': 'ON', '02:30:00': 'ON', '11:00:00': 'RTH'}

# new column to assign the text strings

df['Session'] = df['Time'].map(time_dictionary)

您正试图在数据帧中创建一个新列,该列基于某个特定交易是发生在“on”或“RTH”的正常交易时间内。你建议使用字典来做这件事,但这里有一个解决方案,只检查交易是否发生在交易日的开始和结束之间。你知道吗

import pandas as pd
import datetime

# Create dataframe with example dates
df = pd.DataFrame(data=['2019-09-04T02:15:00Z','2019-09-04T10:30:00Z','2019-09-04T19:00:00Z'],columns=['Date'])

# Convert string date to datetime object
df["Date"] = pd.to_datetime(df["Date"])

# Extract just time time portion of the datetime object
df["Time"] = df["Date"].dt.time

# Create new column based on new time column
STARTOFDAY = datetime.time(9,0)
ENDOFDAY = datetime.time(16,0)
df['Session']=['RTH' if STARTOFDAY <= x <= ENDOFDAY else 'ON' for x in df.Time]

# View result
print(df)

这将返回:

                       Date      Time Session
0 2019-09-04 02:15:00+00:00  02:15:00      ON
1 2019-09-04 10:30:00+00:00  10:30:00     RTH
2 2019-09-04 19:00:00+00:00  19:00:00      ON

我假设交易日从9:00开始到16:00结束。如果您的交易时段不同,您可以更改STARTOFDAY和ENDOFDAY的值。你知道吗

相关问题 更多 >