In the datetime module, the datetime, time, and timedelta classes all have the smallest resolution of microseconds:

>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2009, 12, 4, 23, 3, 27, 343000)
>>> now.microsecond
343000

if you want to display a datetime with fractional seconds, just insert a decimal point and strip trailing zeros:

>>> now.strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')
'2009-12-04 23:03:27.343'

the datetime and time classes only accept integer input and hours, minutes and seconds must be between 0 to 59 and microseconds must be between 0 and 999999. The timedelta class, however, will accept floating point values with fractions and do all the proper modulo arithmetic for you:

>>> span = timedelta(seconds=3662.567)
>>> span
datetime.timedelta(0, 3662, 567000)

The basic components of timedelta are day, second and microsecond (0, 3662, 567000 above), but the constructor will also accept milliseconds, hours and weeks. All inputs may be integers or floats (positive or negative). All arguments are converted to the base units and then normalized so that 0 <= seconds < 60 and 0 <= microseconds < 1000000.

You can add or subtract the span to a datetime or time instance or to another span. Fool around with it, you can probably easily come up with some functions or classes to do exaxtly what you want. You could probably do all your date/time processing using timedelta instances relative to some fixed datetime, say basetime = datetime(2000,1,1,0,0,0), then convert to a datetime or time instance for display or storage.

Answer from Don O'Donnell on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › library › datetime.html
datetime — Basic date and time types
'milliseconds': Include full time, but truncate fractional second part to milliseconds. HH:MM:SS.sss format. 'microseconds': Include full time in HH:MM:SS.ffffff format. ... Excluded time components are truncated, not rounded.
Top answer
1 of 4
53

In the datetime module, the datetime, time, and timedelta classes all have the smallest resolution of microseconds:

>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.datetime(2009, 12, 4, 23, 3, 27, 343000)
>>> now.microsecond
343000

if you want to display a datetime with fractional seconds, just insert a decimal point and strip trailing zeros:

>>> now.strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')
'2009-12-04 23:03:27.343'

the datetime and time classes only accept integer input and hours, minutes and seconds must be between 0 to 59 and microseconds must be between 0 and 999999. The timedelta class, however, will accept floating point values with fractions and do all the proper modulo arithmetic for you:

>>> span = timedelta(seconds=3662.567)
>>> span
datetime.timedelta(0, 3662, 567000)

The basic components of timedelta are day, second and microsecond (0, 3662, 567000 above), but the constructor will also accept milliseconds, hours and weeks. All inputs may be integers or floats (positive or negative). All arguments are converted to the base units and then normalized so that 0 <= seconds < 60 and 0 <= microseconds < 1000000.

You can add or subtract the span to a datetime or time instance or to another span. Fool around with it, you can probably easily come up with some functions or classes to do exaxtly what you want. You could probably do all your date/time processing using timedelta instances relative to some fixed datetime, say basetime = datetime(2000,1,1,0,0,0), then convert to a datetime or time instance for display or storage.

2 of 4
6

A different, non mentioned approach which I like:

from datetime import datetime
from time import sleep

t0 = datetime.now()
sleep(3)
t1 = datetime.now()
tdelta = t1 - t0
print(tdelta.total_seconds())
# will print something near (but not exactly 3)
# 3.0067
Discussions

How can I convert decimal seconds into a format of either H:MM:SS or M:SS, based on if the total duration being converted is greater than an hour or not?
Take it step by step. Write code to calculate minutes and seconds from seconds. This should be two equations. Then write code to convert hours and minutes from minutes. This should also be two equations. Then print a formatted string with the values calculated. More on reddit.com
🌐 r/learnpython
8
3
March 13, 2022
python - datetime: Round/trim number of digits in microseconds - Stack Overflow
To round to 3 places of decimals in seconds, you want to add 0.0005 seconds = 500 microseconds. Here are 3 examples: first, round 0.1234 seconds to 0.123, then round 0.1235 seconds to 0.124, then have the carry propagate all the way when you should be kissing someone to wish them happy new year and instead you're doing Python: >>> r = datetime... More on stackoverflow.com
🌐 stackoverflow.com
python - string to time with decimal seconds - Stack Overflow
Say I have a string with format HHMMSS.SS how do I convert this to a time object? This is how I thought you would do it: import time time.strptime(timestring, '%H%M%S') However%S does not take take More on stackoverflow.com
🌐 stackoverflow.com
datetime.fromisoformat() only accepts 3 or 6 decimal places for fractional seconds
The ISO 8601 spec allows any number of decimal places for fractional seconds, but the datetime.fromisoformat() method raises a ValueError if there is a fractional part that has something other than 3 or 6 decimal places (I checked the so... More on github.com
🌐 github.com
5
July 24, 2022
🌐
Python
bugs.python.org › issue17139
Issue 17139: dateTime.now() return format missing decimal seconds. - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/61341
🌐
DEV Community
dev.to › adamlombard › python-formatting-dates-and-times-3ch2
Python: Formatting dates and times - DEV Community
March 20, 2024 - Python datetime objects contain the following information, in order: Year, Month, Day, Hour, Minute, Second, Millisecond, and Timezone. Let's generate the datetime for May 4, 9876, at exactly 1.001 seconds after 3:02AM, in Los Angeles.
🌐
Google Groups
groups.google.com › g › openrefine › c › uU6O3OG4eng
How to use toDate to convert Timestamp with decimal seconds
If you give it more precision, as in your example, the decimal part (.5550) will be interpreted as 5 seconds and 550 milliseconds. Your result will be wrong. Two solutions at first sight: - Use the datetime Python module mentioned above, which has microsecond precision.
Find elsewhere
🌐
Python
peps.python.org › pep-0410
PEP 410 – Use decimal.Decimal type for timestamps | peps.python.org
February 1, 2012 - The timespec type was rejected because it only supports nanosecond resolution and requires to implement each arithmetic operation, whereas the Decimal type is already implemented and well tested. Add a string argument to function returning timestamps, example: time.time(format=”datetime”).
🌐
GitHub
github.com › python › cpython › issues › 95221
datetime.fromisoformat() only accepts 3 or 6 decimal places for fractional seconds · Issue #95221 · python/cpython
July 24, 2022 - The ISO 8601 spec allows any number of decimal places for fractional seconds, but the datetime.fromisoformat() method raises a ValueError if there is a fractional part that has something other than 3 or 6 decimal places (I checked the source code).
Author   rdfguy
🌐
Python
docs.python.org › 3 › library › time.html
time — Time access and conversions
The %f format directive only applies to strptime(), not to strftime(). However, see also datetime.datetime.strptime() and datetime.datetime.strftime() where the %f format directive applies to microseconds.
🌐
strftime
strftime.org
Python strftime reference cheatsheet
To see the full set of format codes supported on your platform, consult the strftime(3) documentation. The Python docs contain all the format codes that the C standard (1989 version) requires, and these work on all platforms with a standard C implementation. Note that the 1999 version of the C standard added additional format codes.
🌐
Stack Overflow
stackoverflow.com › questions › 68237729 › how-to-format-this-date-time-variable-to-include-on-milliseconds-up-to-2-decimal
python - How to format this date.time variable to include on milliseconds up to 2 decimal places? - Stack Overflow
Copyimport datetime import time def format_timedelta(td): """ Format a timedelta into this format D:H:M:SS.ss """ days = td.days hours, remainder = divmod(td.seconds, 3600) minutes, seconds = divmod(remainder, 60) seconds += td.microseconds / 1e6 return (f'{days}:{hours}:{minutes}:{seconds:02.2f}' if days else f'{hours}:{minutes}:{seconds:02.2f}') begin = datetime.datetime.now() time.sleep(0.123) # 123 ms end = datetime.datetime.now() time_taken = end - begin print(format_timedelta(time_taken)) # -> 0:0:0.12
🌐
Programiz
programiz.com › python-programming › datetime › strftime
Python strftime() - datetime to string
The strftime() method takes one or more format codes as an argument and returns a formatted string based on it. We imported datetime class from the datetime module.
🌐
Mimo
mimo.org › glossary › python › datetime
Python datetime Module: Working with Dates, Times, and Formatting
September 19, 2024 - The Python date and time module provides several classes for formatting and manipulating date and time values. ... from datetime import datetime # Get the current date and time now = datetime.now() print(now) # Outputs: 2024-09-19 12:34:56.789123 · datetime: The module name and main class for working with date and time values. date: Represents a date (year, month, and day) without a time component. time: Represents a time (hours, minutes, seconds, and microseconds) without a date component.
🌐
GitHub
github.com › pandas-dev › pandas › issues › 55321
BUG: to_datetime drops decimal point and fractional seconds under certain conditions · Issue #55321 · pandas-dev/pandas
September 28, 2023 - ''' ``When a column that represents ... it to: 2021-09-17 22:07:15+00:00 · which drops the decimal point and fractional part of the number of seconds in the datetime representation....
Author   DaveSprague
🌐
Studytonight
studytonight.com › python-howtos › how-to-convert-a-datetime-object-to-seconds
How to convert a datetime object to seconds? - Studytonight
February 16, 2021 - import datetime time = "01:01:09" date_time = datetime.datetime.strptime(time, "%H:%M:%S") a_timedelta = date_time - datetime.datetime(1900, 1, 1) seconds = a_timedelta.total_seconds() print(seconds) ...