search
Search
Login
Math ML Join our weekly DS/ML newsletter
menu
menu search toc more_vert
Robocat
Guest 0reps
Thanks for the thanks!
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
help Ask a question
Share on Twitter
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
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to
A
A
brightness_medium
share
arrow_backShare
Twitter
Facebook

Converting datetime column to date and time columns in Pandas

Pandas
chevron_right
Cookbooks
chevron_right
DataFrame Cookbooks
chevron_right
Time Series Cookbook
schedule Jul 1, 2022
Last updated
local_offer PythonPandas
Tags
tocTable of Contents
expand_more

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
A
0 2021-12-25 15:30:00
1 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 1
0 25-12-21 15:30
1 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:30
1 26-12-21 08:00
Name: A, dtype: object

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

mail
Join our newsletter for updates on new DS/ML comprehensive guides (spam-free)
robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!