【问题标题】:How to add date and time information to time series data using python numpy or pandas如何使用 python numpy 或 pandas 将日期和时间信息添加到时间序列数据
【发布时间】:2013-10-13 03:24:54
【问题描述】:

在 pandas 中使用日期和时间计算时遇到问题。

我认为有一些逻辑可以从特定日期和时间开始自动计算持续时间。但是还是没找到。

我想知道如何将日期和时间信息添加到持续时间为 1 秒的时间序列数据中。

Before:
10
12
13
..
20
21
19
18

After:
1013-01-01 00:00:00 10
1013-01-01 00:00:01 12
1013-01-01 00:00:02 13
..
1013-10-04 12:45:40 20
1013-10-04 12:45:41 21
1013-10-04 12:45:42 19
1013-10-04 12:45:43 18

任何帮助将不胜感激。 提前谢谢你。

【问题讨论】:

    标签: python time numpy pandas series


    【解决方案1】:

    documentation 在开头使用date_range 给出了类似的示例。如果你有一个Series 对象,你可以在适当的时间开始创建一个DatetimeIndex(我假设10132013 的错字),频率为一秒,长度适当:

    >>> x = pd.Series(np.random.randint(8,24,23892344)) # make some random data
    >>> when = pd.date_range(start=pd.datetime(2013,1,1),freq='S',periods=len(x))
    >>> when
    <class 'pandas.tseries.index.DatetimeIndex'>
    [2013-01-01 00:00:00, ..., 2013-10-04 12:45:43]
    Length: 23892344, Freq: S, Timezone: None
    

    然后我们可以使用这个作为新索引从原始数据中创建一个新系列:

    >>> x_with_time = pd.Series(x.values, index=when)
    >>> x_with_time
    2013-01-01 00:00:00    13
    2013-01-01 00:00:01    14
    2013-01-01 00:00:02    15
    2013-01-01 00:00:03    22
    2013-01-01 00:00:04    16
    [...]
    2013-10-04 12:45:41    21
    2013-10-04 12:45:42    16
    2013-10-04 12:45:43    15
    Freq: S, Length: 23892344
    

    【讨论】:

    • 非常感谢您的建议!
    • 更简单的方法是以dateutil 可以解析的格式写入日期,这是大多数人类可读的格式:date_range('2013/1/1', ...)
    【解决方案2】:

    如何结合使用 python 的 datetime 模块和时间戳?

    from datetime import datetime
    
    START_TIME = 1381069963.506736
    secs = [10, 12, 13, 20, 21, 19, 18]
    dates = [datetime.fromtimestamp(START_TIME + sec) for sec in secs]
    

    在此之后,日期列表是带有START_TIME + &lt;given interval from time series data&gt;的日期时间对象列表

    【讨论】:

    • 感谢您的帮助!我去看看!
    猜你喜欢
    • 2018-10-20
    • 2018-07-19
    • 2017-11-17
    • 2018-02-02
    • 2021-11-07
    • 2015-05-25
    • 2013-09-18
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多