gpt4 book ai didi

python - 从 DateTimeIndex 中截断毫秒

转载 作者:行者123 更新时间:2023-12-01 09:24:05 27 4
gpt4 key购买 nike

当我使用pandas.date_range()时,有时我的时间戳有很多我不想保留的毫秒数。

假设我...

import pandas as pd
dr = pd.date_range('2011-01-01', '2011-01-03', periods=15)
>>> dr
DatetimeIndex([ '2011-01-01 00:00:00',
'2011-01-01 03:25:42.857142784',
'2011-01-01 06:51:25.714285824',
'2011-01-01 10:17:08.571428608',
'2011-01-01 13:42:51.428571392',
'2011-01-01 17:08:34.285714176',
'2011-01-01 20:34:17.142857216',
'2011-01-02 00:00:00',
'2011-01-02 03:25:42.857142784',
'2011-01-02 06:51:25.714285824',
'2011-01-02 10:17:08.571428608',
'2011-01-02 13:42:51.428571392',
'2011-01-02 17:08:34.285714176',
'2011-01-02 20:34:17.142857216',
'2011-01-03 00:00:00'],
dtype='datetime64[ns]', freq=None)

为了忽略当前的毫秒数,我被迫这样做。

>>> t = []
>>> for item in dr:
... idx = str(item).find('.')
... if idx != -1:
... item = str(item)[:idx]
... t.append(pd.to_datetime(item))
...
>>> t
[Timestamp('2011-01-01 00:00:00'),
Timestamp('2011-01-01 03:25:42'),
Timestamp('2011-01-01 06:51:25'),
Timestamp('2011-01-01 10:17:08'),
Timestamp('2011-01-01 13:42:51'),
Timestamp('2011-01-01 17:08:34'),
Timestamp('2011-01-01 20:34:17'),
Timestamp('2011-01-02 00:00:00'),
Timestamp('2011-01-02 03:25:42'),
Timestamp('2011-01-02 06:51:25'),
Timestamp('2011-01-02 10:17:08'),
Timestamp('2011-01-02 13:42:51'),
Timestamp('2011-01-02 17:08:34'),
Timestamp('2011-01-02 20:34:17'),
Timestamp('2011-01-03 00:00:00')]

有更好的方法吗?我已经尝试过这个...

  1. dr = [ pd.to_datetime(item, format='%Y-%m-%d %H:%M:%S') for item in dr ]

但它没有做任何事情。

  • (pd.date_range('2011-01-01', '2011-01-03', period=15)).astype('datetime64[s]')
  • 但它说它无法转换它。

  • dr = (dr.to_series()).apply(lambda x:x.replace(microseconds=0))
  • 但是这一行并没有解决我的问题,因为...

    2018-04-17 15:07:04.777777664 gives --> 2018-04-17 15:07:04.000000664

    最佳答案

    我相信需要DatetimeIndex.floor :

    print (dr.floor('S'))
    DatetimeIndex(['2011-01-01 00:00:00', '2011-01-01 03:25:42',
    '2011-01-01 06:51:25', '2011-01-01 10:17:08',
    '2011-01-01 13:42:51', '2011-01-01 17:08:34',
    '2011-01-01 20:34:17', '2011-01-02 00:00:00',
    '2011-01-02 03:25:42', '2011-01-02 06:51:25',
    '2011-01-02 10:17:08', '2011-01-02 13:42:51',
    '2011-01-02 17:08:34', '2011-01-02 20:34:17',
    '2011-01-03 00:00:00'],
    dtype='datetime64[ns]', freq=None)

    关于python - 从 DateTimeIndex 中截断毫秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50582589/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com