python pandas date time conversion to date

允我心安 提交于 2021-02-05 01:53:57

问题


I am looking to convert datetime to date for a pandas datetime series.

I have listed the code below:

df = pd.DataFrame()

df = pandas.io.parsers.read_csv("TestData.csv", low_memory=False)

df['PUDATE'] = pd.Series([pd.to_datetime(date) for date in df['DATE_TIME']])

df['PUDATE2'] = datetime.datetime.date(df['PUDATE'])  #Does not work

Can anyone guide me in right direction?


回答1:


You can access the datetime methods of a Pandas series by using the .dt methods (in a aimilar way to how you would access string methods using .str. For your case, you can extract the date of your datetime column as:

df['PUDATE'].dt.date



回答2:


This is a simple way to get day of month, from a pandas

    #create a dataframe with dates as a string

    test_df = pd.DataFrame({'dob':['2001-01-01', '2002-02-02', '2003-03-03', '2004-04-04']})

    #convert column to type datetime
    test_df['dob']= pd.to_datetime(test_df['dob'])

    # Extract day, month , year  using dt accessor
    test_df['DayOfMonth']=test_df['dob'].dt.day
    test_df['Month']=test_df['dob'].dt.month
    test_df['Year']=test_df['dob'].dt.year



回答3:


I think you need to specify the format for example

df['PUDATE2']=datetime.datetime.date(df['PUDATE'], format='%Y%m%d%H%M%S')

So you just need to know what format you are using



来源:https://stackoverflow.com/questions/33379439/python-pandas-date-time-conversion-to-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!