【问题标题】:Convert number of miliseconds from midnight from datetime objct using pandas使用 pandas 从 datetime 对象转换从午夜开始的毫秒数
【发布时间】:2021-01-23 14:32:26
【问题描述】:

我有日期时间索引

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)

我想创建一个新列,表示从午夜开始的毫秒数。

对于秒时间范围 Get the time spent since midnight in dataframe 有一种解决方案,但我无法将其转换为毫秒。

【问题讨论】:

  • df['milliseconds'] = df['seconds'] * 1000
  • 但是 -05:00 毫秒不是时间范围的一部分吗?
  • -05:00 似乎是与 GMT 的偏差

标签: python pandas time


【解决方案1】:

试试

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

输出

    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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 2023-01-12
    • 2012-08-12
    • 1970-01-01
    • 2018-03-11
    • 2011-06-09
    相关资源
    最近更新 更多