Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

python - Convert number of miliseconds from midnight from datetime objct using pandas

I have datetime index

import pandas as pd
sample = ['2021-01-19 15:55:00-05:00',
          '2021-01-19 15:56:00-05:00',
          '2021-01-19 15:56:00-05:00']
sample = pd.to_datetime(sample)

I would like to create new column that represents time measured in the number of milliseconds since midnight.

There is one solution for seconds timeframe Get the time spent since midnight in dataframe but I was not able to convert it to miliseconds.

question from:https://stackoverflow.com/questions/65860375/convert-number-of-miliseconds-from-midnight-from-datetime-objct-using-pandas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try

df = pd.DataFrame(sample, columns=['time'])
df['time'] = pd.to_datetime(df['time'])
df['milliseconds'] = df['time'].apply(lambda x: (x.hour * 3600 + x.minute * 60 + x.second)*1000)

df

output

    time                        milliseconds
0   2021-01-19 15:55:00-05:00   57300000
1   2021-01-19 15:56:00-05:00   57360000
2   2021-01-19 15:56:00-05:00   57360000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...