Home > Back-end >  Converting Milliseconds into Clocktime Format
Converting Milliseconds into Clocktime Format

Time:05-05

I've been trying to convert a milliseconds (0, 5000, 10000) column into a new column with the format: 00:00:00 (00:00:05, 00:00:10 etc)

I tried datetime.datetime.fromtimestamp(5000/1000.0) but it didn't give me the format I wanted. Any help appreciated!

CodePudding user response:

The best is probably to convert to TimeDelta (using pandas.to_timedelta).

Thus you'll benefit from the timedelta object properties

s = pd.Series([0, 5000, 10000])
s2 = pd.to_timedelta(s, unit='ms')

output:

0   0 days 00:00:00
1   0 days 00:00:05
2   0 days 00:00:10
dtype: timedelta64[ns]

If you really want the '00:00:00' format, use instead pandas.to_datetime:

s2 = pd.to_datetime(s, unit='ms').dt.time

output:

0    00:00:00
1    00:00:05
2    00:00:10
dtype: object

optionally with .astype(str) to have strings

CodePudding user response:

Convert values to timedeltas by to_timedelta:

df['col'] = pd.to_timedelta(df['col'], unit='ms')
print (df)
                  col
0 0 days 00:00:00
1 0 days 00:00:05
2 0 days 00:00:10
  • Related