使用pandas.to_datetime转换时是否可以设置日期?

3

我有一个数组,看起来像这样:

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?

4个回答

3

不要使用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]

谢谢。我不知道有to_timedelta方法。今天我因为你学到了有用的东西! - maynull

2

试试这个:

df['Date'] = pd.to_datetime( df['Date'].str.decode("utf-8") ).apply(lambda x: x.replace(year=2015, month=1, day=25))

采用 @Wen 的解决方案以确保正确性 :)


1
不错的使用方法。更多参考请查看 https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timestamp.replace.html - BENY
@Connor John 感谢你的答案。但是当我尝试时,我收到了以下错误:TypeError: replace() got an unexpected keyword argument 'year' - maynull
1
@maynull 在这里需要使用 apply,将 pd.to_datetime(df['Date'].str.decode("utf-8")).apply(lambda x : x.replace(year=2015, month=1, day=25)) 应用到你的代码中。 - BENY
@Wen 那就是我所缺失的。谢谢! 这就是你所需要的。 - Connor John
@maynull 嗯,添加一种修复日期的方法 :-) - BENY
显示剩余2条评论

1
您可以创建一个包含完整日期时间的字符串并进行解析,例如:
df = pd.DataFrame( array )
df['Date'] = pd.to_datetime( '20150125 ' + df['Date'].str.decode("utf-8") )

0

嗯,看起来它工作了 :-)

pd.to_datetime(df['Date'].str.decode("utf-8"))-(pd.to_datetime('today')-pd.to_datetime('2015-01-25'))
Out[376]: 
0   2015-01-25 03:35:05.397191
1   2015-01-25 03:35:06.184700
2   2015-01-25 03:35:08.642503
3   2015-01-25 05:47:15.285806
4   2015-01-25 05:47:20.189460
5   2015-01-25 05:47:30.598514
Name: Date, dtype: datetime64[ns]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接