0

I’m having an issue getting some timestamps into a consistent format.

I have the timestamps: ‘00:00:02.285932’ ‘00:00:07’ ‘00:00:11.366717’ ‘00:00:11.367594’ In pandas from a CSV file. I would like the second line to be consistent with the others. ‘00:00:07.000000’

If I run: timestps.pd.to_datetime(timestps) over the timestps data I do get the format with all the decimals, but it adds a date, which I can’t seem to remove without losing the time format. Any help would be appreciated. Thanks

1 Answers1

0

you can either use datetime and simply not use the year/month/day in your code or convert to timedelta. methods available for both types are different so the choice depends on what you want to do... Ex:

import pandas as pd
# example series:
s = pd.Series(['00:00:02.285932', '00:00:07', '00:00:11.366717', '00:00:11.367594'])

# cast string to datetime:
s_dt = pd.to_datetime(s)
### extract a certain attribute:
# s_dt.dt.second
# 0     2
# 1     7
# 2    11
# 3    11

### format to string for display:
# s_dt.dt.strftime('%H:%M:%S.%f')
# 0    00:00:02.285932
# 1    00:00:07.000000
# 2    00:00:11.366717
# 3    00:00:11.367594
# dtype: object

# cast string to timedelta:
s_td = pd.to_timedelta(s)
# s_td
# 0   00:00:02.285932
# 1          00:00:07
# 2   00:00:11.366717
# 3   00:00:11.367594
# dtype: timedelta64[ns]

### extract total seconds as float:
# s_td.dt.total_seconds()
# 0     2.285932
# 1     7.000000
# 2    11.366717
# 3    11.367594
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Thanks Mr Fuppes I was working with a few of those examples, however they don't return the time format in the full 15 character format without the dates: ‘00:00:07.000000’ – Michael Reilley May 26 '20 at 02:48
  • @MichaelReilley: what do you mean by "15 character format"? If you convert to timedelta or datetime, data is not represented as characters (string) anymore. If the microseconds aren't *displayed* for a timedelta, that simply means they are zero. For datetime objects, use strftime if you want to display them in a certain format (I've added an example, see comments in code). – FObersteiner May 26 '20 at 07:02
  • @MrFuppers Thanks. strftime('%H:%M:%S.%f') solves the issue but wasn't working previously for another reason. A variation of strftime was actually even in the code earlier as well! Thanks again! – Michael Reilley May 30 '20 at 07:48