将时间对象time转换为datetime并将datetime转换为值

2024-05-16 04:34:43 发布

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

嗨,我目前正在处理来自IEX的数据集,似乎无法将时间转换为我可以处理的值。你知道吗

我循环遍历数据帧并将值转换为datetime

for i, row in enumerate(df['label']):
df['date'][i]=datetime.strptime(df['label'][i], format)

这给了我一个新的列,但我只能访问小时/分钟,如果我索引它df['label'][1].hour

当我再次尝试循环以获取值时,我得到一个keyerror:Time

for i, row in enumerate(df['date']):
df['Time'][i]=((df['date'][i].hour -9)*60 +df['date'][i].minute)

Tags: 数据informatdffordatetimedatetime
2条回答

谢谢你们的支持我找到了答案

对于i,枚举中的行(df['date']): df['label'][i]=((df['date'][i].hour-9)*60)+df['date'][i].minute)

这在ipython笔记本中使用Python3实现

import json
import pandas as pd
from pandas import *
import datetime

convert_hour = lambda x: datetime.datetime.strptime(x , '%H:%M %p').strftime('%H') if len(x) > 5 else datetime.datetime.strptime(x , '%I %p').strftime('%H')
df['hour'] = df['label'].apply(convert_hour)
convert_minute = lambda x: datetime.datetime.strptime(x , '%H:%M %p').strftime('%M') if len(x) > 5 else 0
df['minute2'] = df['label'].apply(convert_minute)

相关问题 更多 >