search
Search
Unlock 100+ guides
search toc
close
Outline
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to

# Converting datetime column to date and time columns in Pandas

schedule Aug 12, 2023
Last updated
local_offer
PythonPandas
Tags
expand_more
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

Consider the following DataFrame with a `datetime` column:

``` df = pd.DataFrame({"A":pd.to_datetime(["2021/12/25 15:30","2021/12/26 08:00"])})df A0 2021-12-25 15:30:001 2021-12-26 08:00:00 ```

# Solution

To split `datetime` column `A` into two columns `date` and `time`:

``` df_date_and_time = df['datetime'].dt.strftime("%d-%m-%y %H:%M").str.split(" ", expand=True)df_date_and_time 0 10 25-12-21 15:301 26-12-21 08:00 ```

Here:

• columns `0` and `1` are both of type `Object` (string).

• `expand=True` argument means that we want the `split(~)` method to return a DataFrame

# Explanation

We first convert column `A` into strings holding `date` and `time` information using `strftime(~)`:

``` df["A"].dt.strftime("%d-%m-%y %H:%M") 0 25-12-21 15:301 26-12-21 08:00Name: A, dtype: object ```

We then use the `Series.str.split(~)` method to split each string by space.

Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!