Helene
Helene

Reputation: 49

Converting Milliseconds into Clocktime Format

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!

Upvotes: 0

Views: 111

Answers (2)

jezrael
jezrael

Reputation: 863156

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

Upvotes: 1

mozway
mozway

Reputation: 261820

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

Upvotes: 1

Related Questions