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?
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.
To convert a datetime to a date, you can use the CONVERT() , TRY_CONVERT() , or CAST() function.
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.
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With