I have a dataframe that can be simplified as:
date id 0 02/04/2015 02:34 1 1 06/04/2015 12:34 2 2 09/04/2015 23:03 3 3 12/04/2015 01:00 4 4 15/04/2015 07:12 5 5 21/04/2015 12:59 6 6 29/04/2015 17:33 7 7 04/05/2015 10:44 8 8 06/05/2015 11:12 9 9 10/05/2015 08:52 10 10 12/05/2015 14:19 11 11 19/05/2015 19:22 12 12 27/05/2015 22:31 13 13 01/06/2015 11:09 14 14 04/06/2015 12:57 15 15 10/06/2015 04:00 16 16 15/06/2015 03:23 17 17 19/06/2015 05:37 18 18 23/06/2015 13:41 19 19 27/06/2015 15:43 20
It can be created using:
tempDF = pd.DataFrame({ 'id': [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], 'date': ["02/04/2015 02:34","06/04/2015 12:34","09/04/2015 23:03","12/04/2015 01:00","15/04/2015 07:12","21/04/2015 12:59","29/04/2015 17:33","04/05/2015 10:44","06/05/2015 11:12","10/05/2015 08:52","12/05/2015 14:19","19/05/2015 19:22","27/05/2015 22:31","01/06/2015 11:09","04/06/2015 12:57","10/06/2015 04:00","15/06/2015 03:23","19/06/2015 05:37","23/06/2015 13:41","27/06/2015 15:43"]})
Data has the following types:
tempDF.dtypes date object id int64 dtype: object
I set the 'date' variable to the Pandas datefime64 format (if this is the correct way to describe it) using:
import numpy as np import pandas as pd tempDF['date'] = pd_to_datetime(tempDF['date'])
So now the dtypes look like this:
tempDF.dtypes date datetime64[ns] id int64 dtype: object
I want to change the clock of the original date data. I can use .normalize () to convert to midnight through .dt accessor:
tempDF['date'] = tempDF['date'].dt.normalize()
And I can access individual datetime components (e.g. year) using:
tempDF['date'].dt.year
This gives:
0 2015 1 2015 2 2015 3 2015 4 2015 5 2015 6 2015 7 2015 8 2015 9 2015 10 2015 11 2015 12 2015 13 2015 14 2015 15 2015 16 2015 17 2015 18 2015 19 2015 Name: date, dtype: int64
The question is, how can I change the specific components of a date and time? For example, how can I change noon (12:00) for all dates? I found that datetime.datetime has a .replace () function. However, when converting dates to Pandas format, it makes sense to save in this format. Is there a way to do this without changing the format again?