time data 42:53.700 does not match format %H:%M:%S.%f (match)

2024/11/15 11:38:55

I am trying to convert a column in string format to DateTime format, However, I am getting the following error, could somebody please help?

The error:time data '42:53.700' does not match format '%H:%M:%S.%f' (match)

Code:

Merge_df['Time'] = pd.to_datetime(Merge_df['Time'], format='%H:%M:%S.%f')

enter image description here

Answer

You'll need to clean the data to get a common format before you can parse to data type 'datetime'. For example you can remove the colons and fill with zeros, then parse with the appropriate directive:

import pandas as pddf = pd.DataFrame({'time': ["1:45.333", "45:22.394", "4:55:23.444", "23:44:01.004"]})df['time'] = pd.to_datetime(df['time'].str.replace(':', '').str.zfill(10), format="%H%M%S.%f")df['time']
0   1900-01-01 00:01:45.333
1   1900-01-01 00:45:22.394
2   1900-01-01 04:55:23.444
3   1900-01-01 23:44:01.004
Name: time, dtype: datetime64[ns]

Since the data actually looks more like a duration to me, here's a way how to convert to data type 'timedelta'. You'll need to ensure HH:MM:SS.fff format which is a bit more work:

# ensure common string length
df['time'] = df['time'].str.zfill(12) 
# ensure HH:MM:SS.fff format
df['time'] = df['time'].str[:2] + ":" + df['time'].str[3:5] + ":" + df['time'].str[6:]df['timedelta'] = pd.to_timedelta(df['time'])df['timedelta']
0   0 days 00:01:45.333000
1   0 days 00:45:22.394000
2   0 days 04:55:23.444000
3   0 days 23:44:01.004000
Name: timedelta, dtype: timedelta64[ns]

The advantage of using timedelta is that you can now also handle hours greater 23.

https://en.xdnf.cn/q/119317.html

Related Q&A

How can I import .py file? [duplicate]

This question already has answers here:Adding a directory to sys.path with pathlib(4 answers)Closed last year.Below is my code: from pathlib import Path import os import sys sys.path.insert(0, os.path.…

python: convenient way to create list of strings of repeated elements

How can I create a list like this:["a","a","a",... (repeating "a" a hundred times") "b","b","b",(repeating "b" a hun…

An accurate python sleep function

Ive tried time.sleep(), but its accuracy is total garbage. Consider this loop, for instance:for i in range(10000000):print(i)sleep(.334)Watch the numbers it prints. If its anything like my computer, it…

How to map python dictionary key values to each other?

Suppose we have two dictionaries as below: dict_a_to_b = {2:4, 6:9, 9:3} dict_a_to_c = {2: 0.1, 6:0.2, 9: 0.8}How to map these two dictionaries to make dict_c_to_b in python? dict_c_to_b = {0.1:4, 0.2…

Installing Keyrock on Fiware in my Virtual Machine

I want install keyrock and I follow these steps, but in the step three, when I write in the console:sudo python tools/install_venv.pyConsole shows me the next fail:Could you help me, please?

Cartopy error when attempting to plot rivers

When attempting to use Cartopy to plot rivers, Im getting a URL error. Im not even sure the rivers feature will plot what I want...Im attempting to get the Galveston Ship Channel to show on my map. Her…

Have the address of the client in python

My request is : I have my web pages created in python (wherein there is html code), each pages has a button to go to the next page. Is it possible to get the address of the client when we submit an htm…

try/except issue in Python

I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book …

Counting the number of vowels in a string using for loops in Python

Python Code:sentence = input(Enter a string:) vowel = A,a,E,e,I,i,O,o,U,u Count = 0 for vowel in sentence:Count += 1 print(There are {} vowels in the string: \{}\.format(Count,sentence))I am trying to …

Sum the values of specific rows if the rows have same values in specific column

I have a data frame like this:a b c 12456 11 123.1 12678 19 345.67 13278 19 1235.345or in another format <table><tr><td>12456</td><td>11</td><td>1…