Pandas: Convert Timestamp to datetime.date

后端 未结 4 1373
名媛妹妹
名媛妹妹 2020-12-13 06:00

I have a pandas column of Timestamp data

In [27]: train[\"Original_Quote_Date\"][6] 
Out[27]: Timestamp(\'2013-12-25 00:00:00\')

How can ch

相关标签:
4条回答
  • 2020-12-13 06:27

    As of pandas 0.20.3, use .to_pydatetime() to convert any pandas.DateTimeIndex instances to Python datetime.datetime.

    0 讨论(0)
  • 2020-12-13 06:31

    Use the .date method:

    In [11]: t = pd.Timestamp('2013-12-25 00:00:00')
    
    In [12]: t.date()
    Out[12]: datetime.date(2013, 12, 25)
    
    In [13]: t.date() == datetime.date(2013, 12, 25)
    Out[13]: True
    

    To compare against a DatetimeIndex (i.e. an array of Timestamps), you'll want to do it the other way around:

    In [21]: pd.Timestamp(datetime.date(2013, 12, 25))
    Out[21]: Timestamp('2013-12-25 00:00:00')
    
    In [22]: ts = pd.DatetimeIndex([t])
    
    In [23]: ts == pd.Timestamp(datetime.date(2013, 12, 25))
    Out[23]: array([ True], dtype=bool)
    
    0 讨论(0)
  • 2020-12-13 06:33

    Assume time column is in timestamp integer msec format

    1 day = 86400000 ms

    Here you go:

    day_divider = 86400000
    
    df['time'] = df['time'].values.astype(dtype='datetime64[ms]') # for msec format
    
    df['time'] = (df['time']/day_divider).values.astype(dtype='datetime64[D]') # for day format
    
    0 讨论(0)
  • 2020-12-13 06:38

    You can convert a datetime.date object into a pandas Timestamp like this:

    #!/usr/bin/env python3
    # coding: utf-8
    
    import pandas as pd
    import datetime
    
    # create a datetime data object
    d_time = datetime.date(2010, 11, 12)
    
    # create a pandas Timestamp object
    t_stamp = pd.to_datetime('2010/11/12')
    
    # cast `datetime_timestamp` as Timestamp object and compare
    d_time2t_stamp = pd.to_datetime(d_time)
    
    # print to double check
    print(d_time)
    print(t_stamp)
    print(d_time2t_stamp)
    
    # since the conversion succeds this prints `True`
    print(d_time2t_stamp == t_stamp)
    
    0 讨论(0)
提交回复
热议问题