How do I convert timestamp to datetime.date in pandas dataframe?

前端 未结 7 1807
清酒与你
清酒与你 2020-12-03 14:03

I need to merge 2 pandas dataframes together on dates, but they currently have different date types. 1 is timestamp (imported from excel) and the other is datetime.dat

相关标签:
7条回答
  • 2020-12-03 14:40

    I found the following to be the most effective, when I ran into a similar issue. For instance, with the dataframe df with a series of timestmaps in column ts.

    df.ts.apply(lambda x: pd.datetime.fromtimestamp(x).date())
    

    This makes the conversion, you can leave out the .date() suffix for datetimes. Then to alter the column on the dataframe. Like so...

    df.loc[:, 'ts'] = df.ts.apply(lambda x: pd.datetime.fromtimestamp(x).date())
    
    0 讨论(0)
  • 2020-12-03 14:42

    For me this works:

    from datetime import datetime
    df[ts] = [datetime.fromtimestamp(x) for x in df[ts]]
    
    0 讨论(0)
  • 2020-12-03 14:43

    Another question was marked as dupe pointing to this, but it didn't include this answer, which seems the most straightforward (perhaps this method did not yet exist when this question was posted/answered):

    The pandas doc shows a pandas.Timestamp.to_pydatetime method to "Convert a Timestamp object to a native Python datetime object".

    0 讨论(0)
  • 2020-12-03 14:46

    I got some help from a colleague.

    This appears to solve the problem posted above

    pd.to_datetime(df['mydates']).apply(lambda x: x.date())

    0 讨论(0)
  • 2020-12-03 14:46

    Much simpler than above:

    df['mydates'].dt.date
    
    0 讨论(0)
  • 2020-12-03 14:47

    If you need the datetime.date objects... then get them through with the .date attribute of the Timestamp

    pd.to_datetime(df['mydates']).date
    
    0 讨论(0)
提交回复
热议问题