Home > OS >  extract part of a date and put them into a dataframe
extract part of a date and put them into a dataframe

Time:12-21

I would like to know how from a dataframe with a column dedicated to the date how to extract each part of a date (at once instead of df["_Date"].str.match(pattern) for each part) and put them in a dataframe for example:

import pandas as pd

# date: str mm/dd/yyyy
df = pd.DataFrame(data=["12/1/2010 8:26", "12/3/2010 8:28", "12/6/2010 8:28", "02/15/2011 8:34", "02/18/2011 8:34", "03/01/2011 8:34"], columns=["_Date"])
...
print(newDf)
days monthAndYear time
1        12/2010  8:26
3        12/2010  8:28
6        12/2010  8:28
...

CodePudding user response:

The datatype of your column is still string (=object). You need to convert1 it into datetime first,

df["_Date"] = pd.to_datetime(df._Date)

and then you can access the datetime api via .dt and do things like

>>> df["_Date"].dt.day
0     1
1     3
2     6
3    15
4    18
5     1
Name: _Date, dtype: int64

>>> df._Date.dt.month_name()
0    December
1    December
2    December
3    February
4    February
5       March
Name: _Date, dtype: object

etc.


1Note that you might need to set some options of pd.to_datetime in order to get the expected result, see the docs.

  • Related