Convert datetime Object to Seconds, Minutes & Hours in Python (Example)
In this tutorial I’ll explain how to convert a datetime object to seconds, minutes, or hours in the Python programming language.
The tutorial contains the following sections:
Let’s dive right into the Python code!
Example 1: Convert datetime Object to Seconds
This example uses the strptime() function and the second attribute to extract the seconds from a datetime object:
from datetime import datetime # get seconds datetime.strptime("19/11/21 16:30", "%d/%m/%y %H:%M").second # 0
As you can see, our datetime object contains 0 seconds.
Example 2: Convert datetime Object to Minutes
Example 2 uses the strptime() method to return minutes from a date and time object:
# get minutes datetime.strptime("19/11/21 16:30", "%d/%m/%y %H:%M").minute # 30
Example 3: Convert datetime Object to Hours
This example uses the strptime() function once again. This time we are converting our datetime object to hours.
# get hours datetime.strptime("19/11/21 16:30", "%d/%m/%y %H:%M").hour # 16
Video, Further Resources & Summary
Do you need more explanations on the conversion of datetime objects to seconds, minutes, and hours in Python? In this case, you should definitely have a look at the YouTube video of the PyLenin YouTube channel below.
In this video, the speaker explains the strptime and strftime functions:
Furthermore, you can have a look at the other Python tutorials on Statistics Globe:
- Add Seconds, Minutes & Hours to datetime Object
- Convert datetime into String with Milliseconds
- Convert datetime to String without Microsecond Component
- Python Programming Tutorials
This post has shown how to select only seconds, minutes, or hours from datetime objects in Python programming. In case you have additional questions, you may leave a comment below.
This tutorial was created in collaboration with Gottumukkala Sravan Kumar. Please have a look at Gottumukkala’s author page to get more information about his academic background and the other articles he has written for Statistics Globe.
Subscribe to the Statistics Globe Newsletter
Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.
Thank you!
Welcome to the Statistics Globe newsletter. From now on, I’ll send you regular emails about statistics, data science, AI, and programming with R and Python.
I’m Joachim Schork. On this website, I provide statistics tutorials as well as code in Python and R programming.
Statistics Globe Newsletter
Get regular updates on the latest tutorials, offers & news at Statistics Globe. I hate spam & you may opt out anytime: Privacy Policy.
Thank you!
Please check your email inbox and click the confirmation link to complete your subscription. If you don’t see the email within a few minutes, please also check your spam/junk folder.





