【问题标题】:Convert Time part from DateTime in Seconds以秒为单位从 DateTime 转换时间部分
【发布时间】:2018-08-17 15:05:17
【问题描述】:

我是 python 新手。 我有一列datatime 数据。 现在我想创建一个新列,其中只有datetime 的时间部分(以秒为单位)。

我的第一行数据是 2018-08-03 10:53:00,我想在几秒钟内转换 10:53:00,例如 39180 想要存储在新列中。

我的功能是从给定的datetime 对象中获取平均时间。日期可能会有所不同,但我只想要平均时间。

【问题讨论】:

  • 发布您的示例数据和预期输出。
  • This 是具有相同标题的重复问题,this 是回答您稍后关于查找日期时间列的平均时间的问题。

标签: python python-3.x pandas


【解决方案1】:

你可以使用:

df = pd.DataFrame({
    'date': ['2018-08-03 10:53:00','2018-08-03 10:55:00'],
    'b': [10, 11]
})

#if necessary convert to datetime
df['date'] = pd.to_datetime(df['date'])
df['new'] = df['date'].dt.hour * 3600 + df['date'].dt.minute * 60 + df['date'].dt.second
print (df)
    b                date    new
0  10 2018-08-03 10:53:00  39180
1  11 2018-08-03 10:55:00  39300

mean = df['new'].mean()
print (mean)
39240.0

编辑:如果想要直接表示时间:

df['new'] = df['date'].dt.time
print (df)
    b                date       new
0  10 2018-08-03 10:53:00  10:53:00
1  11 2018-08-03 10:55:00  10:55:00

mean = df['new'].mean()
print (mean)

TypeError:+ 不支持的操作数类型:“datetime.time”和“datetime.time”

但日期时间的平均值是可能的 - 在ns 中转换为 unix 时间:

df['new'] = df['date'].values.astype(np.int64)
print (df)
    b                date                  new
0  10 2018-08-03 10:53:00  1533293580000000000
1  11 2018-08-03 10:55:00  1533293700000000000

mean = df['new'].mean()
print (mean)
1.53329364e+18

【讨论】:

  • 感谢人试图找到但没有得到但现在理解并解决了感谢人:)
  • 在python中是否直接有任何可以找到日期时间分量平均值的东西?
【解决方案2】:

这是你想要做的一个例子

randdays = np.random.randint(1,100,10)
randhours = np.random.randint(1,100,10)
randdates = [datetime.now() + timedelta(days=int(i),hours=int(j)) for i,j in zip(randdays,randhours)]
sample_df = pd.DataFrame({'random_dates':randdates})
sample_df['seconds'] = sample_df.random_dates.apply(lambda x: (x-datetime(day=x.day,month=x.month,year=x.year)).seconds)
sample_df

输出

    random_dates                seconds
0   2018-03-13 06:02:52.730957  21772
1   2018-06-17 10:02:52.730957  36172
2   2018-06-12 07:02:52.730957  25372
3   2018-05-09 05:02:52.730957  18172
4   2018-05-23 15:02:52.730957  54172
5   2018-03-29 21:02:52.730957  75772
6   2018-03-17 03:02:52.730957  10972
7   2018-05-16 07:02:52.730957  25372
8   2018-06-11 23:02:52.730957  82972
9   2018-03-10 14:02:52.730957  50572

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-07
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多