Search code examples
pythonpandastimedelta

How to remove microseconds from timedelta


I have microseconds that I want to essentially truncate from a pandas column. I tried something like analyze_me['how_long_it_took_to_order'] = analyze_me['how_long_it_took_to_order'].apply(lambda x: x.replace(microsecond=0) but to this error came up replace() takes no keyword arguments.

For example: I want 00:19:58.582052 to become 00:19:58 or 00:19:58.58

enter image description here


Solution

  • your how_long_it_took_to_order column seems to be of string (object) dtype.

    So try this:

    analyze_me['how_long_it_took_to_order'] = \
        analyze_me['how_long_it_took_to_order'].str.split('.').str[0]
    

    or:

    analyze_me['how_long_it_took_to_order'] = \
        analyze_me['how_long_it_took_to_order'].str.replace('(\.\d{2})\d+', r'\1')
    

    for "centiseconds", like: 00:19:58.58