Convert Seconds, Minutes & Hours to datetime in Python (Example)
On this page, you’ll learn how to convert the inputs of seconds, minutes, and hours to a datetime object in Python programming.
The content list of the tutorial is as follows:
Let’s start right away.
Example Data & Imported Modules
First, we should import the datetime module.
import datetime # Load datetime module
We also should create sample data including seconds, minutes, and hours:
seconds = 35 # Initializing the second field minutes = 45 # Initializing the minutes field hours = 21 # Initializing the hours field
Example: Creation of datetime Object
In this example, I’ll illustrate how to initialize a datetime object. A datetime object has the year, month, and day parameters, and optionally it may have the hour, minute, and second parameters.
As the date is not specified, we will use 1,1,1 for the input of year, month, and day.
dt = datetime.datetime(1,1,1, hours, minutes, seconds) # datetime initialization print(dt) # Print datetime object # 0001-01-01 21:45:35
The previous Python console output shows that the datetime object is successfully created.
Video & Further Resources
Have a look at the following video on my YouTube channel. I’m explaining the content of this article in the video.
The YouTube video will be added soon.
Furthermore, you could have a look at the other articles on my homepage.
- Dates & Times in Python – datetime Module
- Introduction to timedelta Objects in Python
- Add Seconds, Minutes & Hours to datetime Object in Python
- Subtract Seconds, Minutes & Hours from datetime in Python
- Convert datetime Object to Seconds, Minutes & Hours in Python
- All Python Programming Examples
In summary: This tutorial has illustrated how to construct a datetime object with seconds, minutes and hours in Python. If you have further questions, please let me know in the comments section.
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get further information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.