When you have a datetime column, then you're able to parse lots
of information from it. The trick is to refer to the
that's attached to the column.
Here's a few examples.
import pandas as pd df = pd.read_csv("https://calmcode.io/datasets/birthdays.csv") (df .assign(date=lambda d: pd.to_datetime(d['date'], format="%Y-%m-%d"), day_of_week=lambda d: d['date'].dt.day_name(), minute=lambda d: d['date'].dt.minute, nanosecond=lambda d: d['date'].dt.nanosecond, day_of_year=lambda d: d['date'].dt.day_of_year, month_manual=lambda d: d['date'].dt.month, week=lambda d: d['date'].dt.isocalendar().week))
Pay close attention to the
week property. Since pandas 1.10 it's recommended
d['date'].dt.isocalendar().week instead of
There's are lot's of properties that you can access this way. Here's a list of most properties you may want to use.
|year||The year of the datetime|
|month||The month of the datetime|
|day||The days of the datetime|
|hour||The hour of the datetime|
|minute||The minutes of the datetime|
|second||The seconds of the datetime|
|microsecond||The microseconds of the datetime|
|nanosecond||The nanoseconds of the datetime|
|dayofyear||The ordinal day of year|
|weekday||The number of the day of the week with Monday=0, Sunday=6|
|quarter||Quarter of the date: Jan-Mar = 1, Apr-Jun = 2, etc.|
|days_in_month||The number of days in the month of the datetime|
|is_leap_year||Logical indicating if the date belongs to a leap year|
This is a subset of all the properties listed on the pandas documentation.
For a full overview of all
.dt properties, do check the full table on their docs.