【问题标题】:Is possible to set a date when converting with pandas.to_datetime?使用 pandas.to_datetime 转换时可以设置日期吗?
【发布时间】:2018-08-15 02:27:12
【问题描述】:

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

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?

【问题讨论】:

    标签: python pandas hdf5


    【解决方案1】:

    嗯,好像可以了 :-)

    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]
    

    【讨论】:

      【解决方案2】:

      试试这个:

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

      结合@Wen 的正确解决方案:)

      【讨论】:

      • @Connor John 谢谢你的回答。但是当我尝试它时,我得到了这个错误:TypeError: replace() got an unexpected keyword argument 'year'
      • 你是在复制整行代码吗? datetime.replace() 将年份作为参数。我猜它被应用于一个字符串
      • @maynull pd.to_datetime(df['Date'].str.decode("utf-8")).apply(lambda x : x.replace(year=2015, month=1, day=25)),你需要在这里申请
      • @Wen 这就是我所缺少的。谢谢!这就是你需要的
      【解决方案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 方法。多亏了你,我今天学到了一些有用的东西!
      【解决方案4】:

      您可以创建一个包含完整日期时间的字符串并进行解析,例如:

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

      【讨论】:

        猜你喜欢
        • 2013-05-16
        • 2015-01-20
        • 1970-01-01
        • 2013-04-17
        相关资源
        最近更新 更多