【问题标题】:Removing date and keeping time only from timestamp in a uneven pandas column仅从不均匀熊猫列中的时间戳中删除日期和保持时间
【发布时间】:2021-09-04 03:17:42
【问题描述】:

我有以下数据框结构:

我想转换列“Entr”。和“Fim”到时间 (HH:MM),格式为:HH:MM:SS。我在转换时卡住了,因为列不均匀:有时出现“-”,有时是日期时间格式“DD-MM-YYYY HH:MM:SS”,有时是时间“HH:MM:SS”。

列:


列示例:

https://drive.google.com/file/d/1ujvPED0S1vPZ9bmCSob3vR68XwUXC2gk/view?usp=sharing

【问题讨论】:

  • 我有点不清楚。您是要删除有日期的行还是要去掉日期?

标签: python pandas date datetime time


【解决方案1】:

读取 Excel 文件会给您留下混合数据类型的列;一些元素是datetime.datetime 对象(例如datetime.datetime(1900, 1, 1, 0, 10) at df['Fim'].iloc[2]),一些是datetime.time(例如datetime.time(13, 15) at df['Fim'].iloc[0])。与库 xlrd / openpyxl 如何读取文件有关的 AFAIK - pandas 对此无能为力。相关:Pandas read excel returning type object when time is 00:00。

TLDR:

将所有内容转换为字符串并删除日期。这让您有 HH:MM:SS 格式的时间。

df = pd.read_excel(filename)

df['Entr.'] = df['Entr.'].astype(str).str.split(' ').str[-1]
df['Fim'] = df['Fim'].astype(str).str.split(' ').str[-1]
df.head()

      Entr.       Fim
0  05:25:00  13:15:00
1  13:15:00  16:00:00
2  16:00:00  00:10:00
3  03:30:00  11:18:00
4  11:18:00  18:00:00

【讨论】:

    【解决方案2】:

    导入日期工具 dateutil.parser.parse("1900-01-01 02:32:00")

    【讨论】:

    • 另一种方法是使用 time=date.split("\n")[1]
    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 2019-12-18
    • 2021-10-11
    • 2017-02-23
    • 1970-01-01
    • 2023-01-12
    • 2020-01-07
    相关资源
    最近更新 更多