I have a column called Pausetime and another one called Worktime.
Both of them are strings and look like this: "02:28:49".
I want to convert them from strings to date objects; however, keep the format %H%M%S
I am using the following line:

# define the format of the time columns
time_format = "%H:%M:%S"

# convert the time columns
df["Pausetime"] = pd.to_datetime(df["Pausetime"], format=time_format)
df["Worktime"]  = pd.to_datetime(df["Worktime"],  format=time_format)

print(df["Worktime"])

但是,输出不是传递的time_格式

1   1900-01-01 02:28:49
2   1900-01-01 04:47:45
3   1900-01-01 04:49:09
4   1900-01-01 02:46:47
Name: Worktime, dtype: datetime64[ns]

Any Tips on how to achieve this?
I am new to Pandas and kinda lost in this issue.

The reason is I am calculating the time later on in Excel, and apparently, it only works if the cell is date formatted.

推荐答案

如果需要只有时间而没有日期的DateTime对象,这在Python中是不可能的.

您可以将值转换为时间:

df["Pausetime"] = pd.to_datetime(df["Pausetime"], format=time_format).dt.time
df["Worktime"]  = pd.to_datetime(df["Worktime"],  format=time_format).dt.time

print (df['Worktime'])
0    02:28:49
1    04:47:45
2    04:49:09
Name: Worktime, dtype: object

或时间增量,但格式不同:

df["Pausetime"] = pd.to_timedelta(df["Pausetime"])
df["Worktime"]  = pd.to_timedelta(df["Worktime"])

print (df['Worktime'])
0   0 days 02:28:49
1   0 days 04:47:45
2   0 days 04:49:09
Name: Worktime, dtype: timedelta64[ns]

Python相关问答推荐

计算每月过go x年的平均值

如何将自动创建的代码转换为类而不是字符串?

当变量也可以是无或真时,判断是否为假

Pandas read_jsonfuture 警告:解析字符串时,to_datetime与单位的行为已被反对

过载功能是否包含Support Int而不是Support Int?

有什么方法可以避免使用许多if陈述

根据给定日期的状态过滤查询集

大Pandas 胚胎中产生组合

根据条件将新值添加到下面的行或下面新创建的行中

沿着数组中的轴计算真实条目

如何在虚拟Python环境中运行Python程序?

在Python中管理打开对话框

OR—Tools中CP—SAT求解器的IntVar设置值

如何在FastAPI中为我上传的json文件提供索引ID?

可以bcrypts AES—256 GCM加密损坏ZIP文件吗?

为什么if2/if3会提供两种不同的输出?

Flash只从html表单中获取一个值

Matplotlib中的字体权重

如何杀死一个进程,我的Python可执行文件以sudo启动?

合并与拼接并举