将字符串对象格式化为小时:分钟:秒python

2024-09-30 12:22:39 发布

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

我在数据帧timeStarted_timeWhenPuzzlesShownOnScreen中有一个对象,需要将其转换为时间对象。但是,有些值具有不同的格式。我怎么才能到处走呢 在python中将下图中显示的字符串转换为hours:minutes: seconds

enter image description here


Tags: 数据对象字符串格式时间中将secondshours
2条回答

dateutil模块将做您想做的事情,稍微修改一下以整数表示的时间

>>> from dateutil.parser import parser
>>> p = parser()
>>> p.parse("13:35:53")
datetime.datetime(2021, 8, 19, 13, 35, 53)
>>> p.parse("23:05:50")
datetime.datetime(2021, 8, 19, 23, 5, 50)

要将冒号转换为整数,可以执行以下操作

>>> a = str(230550)
>>> f"{a[:2]}:{a[2:4]}:{a[4:]}"
'23:05:50'

很难看,但可能有用

具有此数据帧:

        timeStarted_timeWhenPuzzlesShowScreen
  0                              10:06:43
  1                                113507

如果您运行:

pd.to_datetime(data['timeStarted_timeWhenPuzzlesShowScreen'], \
format='%H:%M:%S',errors='coerce').fillna \
(pd.to_datetime(data['timeStarted_timeWhenPuzzlesShowScreen'], \
format='%H%M%S',errors='coerce'))

您得到的行为datetimes64:

0   1900-01-01 10:06:43
1   1900-01-01 11:35:07
Name: timeStarted_timeWhenPuzzlesShowScreen, dtype: datetime64[ns]

相关问题 更多 >

    热门问题