python - 使用 pandas.to_datetime 转换时可以设置日期吗?

标签 python pandas hdf5

我有一个如下所示的数组:

array([(b'03:35:05.397191'),
    (b'03:35:06.184700'),
    (b'03:35:08.642503'), ...,
    (b'05:47:15.285806'),
    (b'05:47:20.189460'),
    (b'05:47:30.598514')],
    dtype=[('Date', 'S15')])

我想使用 to_datetime 将其转换为数据帧。我可以通过简单地这样做来做到这一点:

df = pd.DataFrame( array )
df['Date'] = pd.to_datetime( df['Date'].str.decode("utf-8") )

>>> df.Date
0      2018-03-07 03:35:05.397191
1      2018-03-07 03:35:06.184700
2      2018-03-07 03:35:08.642503
3      2018-03-07 03:35:09.155030
4      2018-03-07 03:35:09.300029
5      2018-03-07 03:35:09.303031

问题是它会自动将日期设置为今天。是否可以将日期设置为不同的日期,例如 2015-01-25?

最佳答案

不使用 pd.to_datetime,而是使用 pd.to_timedelta 并添加一个日期。

pd.to_timedelta(df.Date.str.decode("utf-8")) + pd.to_datetime('2017-03-15')

0   2017-03-15 03:35:05.397191
1   2017-03-15 03:35:06.184700
2   2017-03-15 03:35:08.642503
3   2017-03-15 05:47:15.285806
4   2017-03-15 05:47:20.189460
5   2017-03-15 05:47:30.598514
Name: Date, dtype: datetime64[ns]

关于python - 使用 pandas.to_datetime 转换时可以设置日期吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49144240/

相关文章:

Python Django equals 在函数参数中。动态设置变量

visual-c++ - 使用 Visual C++ 2013 在 Visual Studio 2013 上开始使用 HDF5

python - 使用 pandas.to_hdf 快速读取 df 中的指定列

python : split a list dynamically

python - 有没有更快的运行 GridsearchCV 的方法

python - 使用线程同时写入多个 CSV 文件

python - cumsum 限制在一个范围内(python,pandas)

python - 如何使用 Pandas 数据框删除不在集群中的值?

python - 在 h5py 数据集中添加或删除特定行或列

python - 从 3D 数组中删除与从 3D 数组中删除的行相对应的行