Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pandas date time conversion to date

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?

like image 767
Krisjay Avatar asked Oct 27 '15 22:10

Krisjay


People also ask

How do I convert datetime to date in Python?

Use the datetime. date() Function to Convert Datetime to Date in Python. The datetime() constructor can be utilized to generate a date. The datetime() constructor has three parameters: day, month, and year.

How do I convert datetime to date?

To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.

How do I convert a timestamp to a date in Python?

Import the “datetime” file to start timestamp conversion into a date. Create an object and initialize the value of the timestamp. Use the ” fromtimestamp ()” method to place either data or object. Print the date after conversion of the timestamp.


3 Answers

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
like image 126
maxymoo Avatar answered Oct 23 '22 09:10

maxymoo


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
like image 23
Sujit Bhattacharyya Avatar answered Oct 23 '22 10:10

Sujit Bhattacharyya


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

like image 36
Alex J Avatar answered Oct 23 '22 10:10

Alex J