python - 如何根据字符串列设置 python pandas 中日期时间列的时间

标签 python pandas datetime

我有一个包含 DateTime 列的 DataFrame,其中包含日期但没有时间 ['date_from']。我的时间在['Time']列(字符串)中。如何仅将时间添加到现有的 DateTime 列中?

我尝试过:

df['date_from'].dt.time = pd.to_datetime(df['Time'], format='%H%M').dt.time

最佳答案

将列转换为to_timedelta并添加到 datetime 列:

#convert to string and if necessary add zero for 4 values
s = df['Time'].astype(str).str.zfill(4)
df['date_from'] += pd.to_timedelta(s.str[:2] + ':' + s.str[2:] + ':00')

示例:

df = pd.DataFrame({'date_from':pd.date_range('2015-01-01', periods=3),
                   'Time':[1501,112, 2012]})

print (df)    
   Time  date_from
0  1501 2015-01-01
1  0112 2015-01-02
2  2012 2015-01-03

s = df['Time'].astype(str).str.zfill(4)
df['date_from'] += pd.to_timedelta(s.str[:2] + ':' + s.str[2:] + ':00')
print (df)
   Time           date_from
0  1501 2015-01-01 15:01:00
1  0112 2015-01-02 01:12:00
2  2012 2015-01-03 20:12:00

关于python - 如何根据字符串列设置 python pandas 中日期时间列的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47177148/

相关文章:

python - 无法使用 strptime() 正确解析微秒

c# - 如何将秒数转换为(小时 :Minutes:Seconds:Milliseconds) time?

python - 何时在 Python 中使用绝对路径与相对路径

python - 从app引擎python查询TXT记录(DNS)

pandas - 我如何使用 scipy optimize curve fit with panda df

python - 如何使用xlsxwriter写入没有数据框的excel文件

python - 在 Pandas DF 中创建按年龄类别分组的新列

php - 如何在 MySQL 中将 DATE 和 TIME 与 DATETIME 分开?

python - 格式化可变长度列表中的字符串

python - 为什么使用合并操作生成的数据帧不是 3x3 维度而不是 3x5 维度?