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:

 

Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.

YouTube Content Consent Button Thumbnail

YouTube privacy policy

If you accept this notice, your choice will be saved and the page will refresh.

 

Furthermore, you can have a look at the other Python tutorials on Statistics Globe:

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.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top