简体   繁体   中英

Formatting string object into hours:minutes:seconds python

I have an object in a data frame timeStarted_timeWhenPuzzlesShownOnScreen and need to convert it into a time object. Some values however have different formats. How would I be able to go about turning the strings shown in the picture below into hours:minutes: seconds in python?

在此处输入图像描述

The dateutil module will do what you want, with a bit of fiddling with the times expressed as integers.

>>> 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)

To get the colons into the integers, you can do

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

Very ugly but it might work.

Having this dataframe:

        timeStarted_timeWhenPuzzlesShowScreen
  0                              10:06:43
  1                                113507

If you run:

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'))

You get the rows as datetimes64:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM