- How to Convert Seconds to Hours, Minutes and Seconds in Python
- Python Date
- Convert seconds to hours, minutes, and seconds
- Example: Using Simple Mathematical Calculations
- Example: Using divmod() function
- Example: Using datetime Module
- Example: Using the time module
- Conclusion
- In Python, how do you convert seconds since epoch to a `datetime` object?
- Time in seconds to python datetime
- # Add seconds to datetime in Python
- # Adding seconds to the current time
- # Add seconds to a datetime object using datetime.combine
- # Extracting the time after the operation
- # Formatting the time as HH:MM:SS
- # Additional Resources
How to Convert Seconds to Hours, Minutes and Seconds in Python
In this article, we will learn to convert seconds to hours, minutes, and seconds in Python. We will use some built-in modules available and some custom codes as well to see them working. Let’s first have a quick look over what are dates in Python.
Python Date
In Python, we can work on Date functions by importing a built-in module datetime available in Python. We have date objects to work with dates. This datetime module contains dates in the form of year, month, day, hour, minute, second, and microsecond. The datetime module has many methods to return information about the date object. It requires date, month, and year values to compute the function. Date and time functions are compared like mathematical expressions between various numbers.
Convert seconds to hours, minutes, and seconds
In Python, the date and time module provides various functions for the manipulation of dates. We can also convert seconds into hours, minutes, and seconds by applying mathematical operations. Let us discuss the various ways to perform the conversion.
Example: Using Simple Mathematical Calculations
It calculates seconds, hours, and minutes individually from the given seconds. Hour is calculated by floor division ( // ) of seconds by 3600. Minutes are calculated by floor division of remaining seconds. Seconds are also calculated by the remainder of hour and minutes calculation. In the print statement, string formatting is done to print in the preferred format.
seconds = 12601 seconds = seconds % (24 * 3600) hour = seconds // 3600 seconds %= 3600 minutes = seconds // 60 seconds %= 60 print("%d:%02d:%02d" % (hour, minutes, seconds))
Example: Using divmod() function
The below example uses divmod() function. This function performs a single division and results in the quotient and the remainder.
seconds = 31045 minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) print("%d:%02d:%02d" % (hours, minutes, seconds))
Example: Using datetime Module
The datetime module of Python provides datetime.timedelta() function to convert seconds into hours, minutes, and seconds. It takes seconds as an argument and prints the seconds in the preferred format.
The timedelta(seconds) is called to convert seconds to a timedelta object and str(object) is called with timedelta object to return a string representing seconds as hours, minutes, and seconds.
import datetime sec = 9506 convert = str(datetime.timedelta(seconds = sec)) print(convert)
Example: Using the time module
The time module of Python provides datetime.strftime() function to convert seconds into hours, minutes, and seconds. It takes time format and time.gmtime() function as arguments.
strftime() — It prints the seconds in the preferred format.
gmtime() — It is used to convert seconds to the specified format that strftime() requires.
import time seconds = 52910 convert = time.strftime("%H:%M:%S", time.gmtime(seconds)) print(convert)
Conclusion
In this article, we learned to convert seconds into hours, minutes, and seconds format by using datetime module, time module and two simple mathematical approaches. We used some custom codes as well to better understand the working of each method.
In Python, how do you convert seconds since epoch to a `datetime` object?
bizarrely, datetime.utcfromtimestamp creates a naive timestamp. I had to import pytz and use datetime.fromtimestamp(1423524051, pytz.utc) to create an aware datetime.
as a follow-on to the above, with Python >= 3.2 you don’t have to import the pytz library if you only want the UTC timestamp — you only need to from datetime import datetime, timezone and then call it as follows: datetime.fromtimestamp(1423524051, timezone.utc) . It has saved the extra library many times when I only need the UTC timezone from pytz .
Seconds since epoch to datetime to strftime :
>>> ts_epoch = 1362301382 >>> ts = datetime.datetime.fromtimestamp(ts_epoch).strftime('%Y-%m-%d %H:%M:%S') >>> ts '2013-03-03 01:03:02'
@vml19, it depends on whether datetime was imported from datetime or not ( import datetime vs. from datetime import datetime ).
From the docs, the recommended way of getting a timezone aware datetime object from seconds since epoch is:
from datetime import datetime, timezone datetime.fromtimestamp(timestamp, timezone.utc)
from datetime import datetime import pytz datetime.fromtimestamp(timestamp, pytz.utc)
A link to the documentation in your subtitles («Python 3», «Python 2») would be useful — and I also recommend changing their order.
Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:
This is a problem. There are many people who are born before 1970 or Dec 31 1969 in the US! Those DOBs stored in Java may break intraoperatively then.
For those that want it ISO 8601 compliant, since the other solutions do not have the T separator nor the time offset (except Meistro‘s answer):
from datetime import datetime, timezone result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds') print(result) # 2016-05-15T05:01:34.000000+00:00
Note, I use fromtimestamp because if I used utcfromtimestamp I would need to chain on .astimezone(. ) anyway to get the offset.
If you don’t want to go all the way to microseconds you can choose a different unit with the isoformat() method.
Time in seconds to python datetime
Last updated: Feb 19, 2023
Reading time · 3 min
# Add seconds to datetime in Python
Use the timedelta() class from the datetime module to add seconds to datetime.
The timedelta class can be passed a seconds argument and adds the specified number of seconds to the datetime object.
Copied!from datetime import datetime, timedelta # ✅ add seconds to a datetime object dt = datetime(2023, 9, 24, 9, 30, 35) print(dt) # 👉️ 2023-09-24 09:30:35 result = dt + timedelta(seconds=24) print(result) # 👉️ 2023-09-24 09:30:59 # ------------------------------ # ✅ add seconds to the current time now = datetime.today() print(now) # 👉️ 2022-12-17 12:56:10.092082 result = now + timedelta(seconds=15) print(result) # 👉️ 2022-12-17 12:56:25.092082
If you only have a time component, e.g. 09:30:13 scroll down to the code sample that uses datetime.combine .
Make sure to import the datetime and timedelta classes from the datetime module.
The first example uses the datetime class to create a datetime object.
We passed values for the year , month , day , hour , minute and second arguments.
Once we have a datetime object, we can use the timedelta class to add seconds to it.
Copied!from datetime import datetime, timedelta # ✅ add seconds to datetime dt = datetime(2023, 9, 24, 9, 30, 35) print(dt) # 👉️ 2023-09-24 09:30:35 result = dt + timedelta(seconds=24) print(result) # 👉️ 2023-09-24 09:30:59
The code sample adds 24 seconds to the datetime object.
# Adding seconds to the current time
If you need to add seconds to the current time, use the datetime.today() method to get a datetime object that stores the current date and time.
Copied!from datetime import datetime, timedelta now = datetime.today() print(now) # 👉️ 2023-02-19 05:23:54.700526 result = now + timedelta(seconds=15) print(result) # 👉️ 2023-02-19 05:24:09.700526
The datetime.today() method returns the current local datetime .
We need to use a datetime object because it automatically rolls over the minutes, hours, days, months and years if necessary.
This wouldn’t be possible if we only had the time component. For example, 11:59:30PM + 50 seconds would raise an exception.
# Add seconds to a datetime object using datetime.combine
If you only have the time component, use the datetime.combine method to combine the time with the current (or some other) date and get a datetime object.
Copied!from datetime import datetime, date, timedelta, time t = time(9, 30, 13) print(t) # 👉️ 09:30:13 result = datetime.combine(date.today(), t) + timedelta(seconds=27) print(result) # 👉️ 2023-02-19 09:30:40 only_t = result.time() print(only_t) # 👉️ 09:30:40
The datetime.combine method takes a date and time as arguments and returns a new datetime object by combining them.
Once we get a datetime object, we can use the timedelta class to add seconds to it.
# Extracting the time after the operation
Use the time() method on the datetime object if you only need to extract the time after the operation.
Copied!from datetime import datetime, date, timedelta, time t = time(9, 30, 13) print(t) # 👉️ 09:30:13 result = datetime.combine(date.today(), t) + timedelta(seconds=27) print(result) # 👉️ 2023-02-19 09:30:40 # ✅ only get updated time only_t = result.time() print(only_t) # 👉️ 09:30:40
The datetime.time method returns a time object with the same hour, minute, second and millisecond.
# Formatting the time as HH:MM:SS
If you need to get the time formatted as HH:MM:SS , use a formatted string literal.
Copied!from datetime import datetime, timedelta now = datetime.now() print(now) # 👉️ 2023-02-19 05:26:12.016596 result = now + timedelta(seconds=10) print(result) # 👉️ 2023-02-19 05:26:22.016596 print(result.time()) # 👉️ 05:26:22.016596 print(f'result:%H:%M:%S>') # 👉️ 05:26:22
Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f .
Make sure to wrap expressions in curly braces — .
Formatted string literals also enable us to use the format specification mini-language in expression blocks.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.