Formatting timedelta objects
But I was wondering if I can do it in a single line using any date time function like
strftime
.
As far as I can tell, there isn't a built-in method to timedelta
that does that. If you're doing it often, you can create your own function, e.g.
def strfdelta(tdelta, fmt):
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
return fmt.format(**d)
Usage:
>>> print strfdelta(delta_obj, "{days} days {hours}:{minutes}:{seconds}")
1 days 20:18:12
>>> print strfdelta(delta_obj, "{hours} hours and {minutes} to go")
20 hours and 18 to go
If you want to use a string format closer to the one used by strftime
we can employ string.Template
:
from string import Template
class DeltaTemplate(Template):
delimiter = "%"
def strfdelta(tdelta, fmt):
d = {"D": tdelta.days}
d["H"], rem = divmod(tdelta.seconds, 3600)
d["M"], d["S"] = divmod(rem, 60)
t = DeltaTemplate(fmt)
return t.substitute(**d)
Usage:
>>> print strfdelta(delta_obj, "%D days %H:%M:%S")
1 days 20:18:12
>>> print strfdelta(delta_obj, "%H hours and %M to go")
20 hours and 18 to go
The
totalSeconds
value is shown as 13374 instead of 99774. I.e. it's ignoring the "day" value.
Note in the example above that you can use timedelta.days
to get the "day" value.
Alternatively, from Python 2.7 onwards, timedelta has a total_seconds() method which return the total number of seconds contained in the duration.
Python format timedelta object to datetime
Don't use str(...)
, but use datetime.strftime
(the serializing counterpart to datetime.strptime
deserialization) with your original format string:
new_datetime = datetime_obj + timedelta(days=1)
print(new_datetime.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
# 2020-11-16T00:00:00.000000Z
Is there a way to format a timedelta object to be hours-minutes-seconds.MILLISECONDS?
Given your initial code example, you could use something like this:
# From your example.
c = b - a
# Get the hours, minutes, and seconds.
minutes, seconds = divmod(c.seconds, 60)
hours, minutes = divmod(minutes, 60)
# Round the microseconds to millis.
millis = round(c.microseconds/1000, 0)
print(f"Doing <something> took {hours}:{minutes:02}:{seconds:02}.{millis}")
which results in
# c = datetime.timedelta(seconds=7, microseconds=319673)
Doing <something> took 0:00:07.320
Take a look at Python’s built-in functions round() and divmod() and please poke around this and this related thread; also, please read through this and this thread to learn more about formatting timedelta objects.
How Do I Format a pandas timedelta object?
See the function strfdelta(tdelta, fmt)
provided as an answer to a related question: https://stackoverflow.com/a/8907269/454773
Using strftime to format datetime.timedelta objects in a dictionary
NOTE: Your example dict contains both int values AND datetime.timedelta values. This is almost certainly not what you mean to do. Initialize your dict with datetime.timedelta() (a 00:00:00 delta) instead of with the value 0.
Instead of {'Monday': 0} you would store {'Monday': timedelta.datetime()}
d = {}
d['key1'] = datetime.timedelta(hours=1, minutes=1, seconds=1)
d['key2'] = datetime.timedelta(hours=2, minutes=2, seconds=2)
d['key3'] = datetime.timedelta(hours=3, minutes=3, seconds=3)
-- print the values, rely on the default string representation of datetime.timedelta --
def serialize_dict(d):
for key,value in d.iteritems():
print '%s: %s' % (key,value)
serialize_dict(d)
#
# output:
# key3: 3:03:03
# key2: 2:02:02
# key1: 1:01:01
--or write to a file --
def serialize_dict(d):
with open('/tmp/output', 'w') as f:
for key, value in d.iteritems():
f.write('%s: %s\n' % (key, value))
How to format duration in Python (timedelta)?
You can do this by converting durationTime
which is a datetime.timedelta
object to a datetime.time
object and then using strftime
.
print datetime.time(0, 0, durationTime.seconds).strftime("%M:%S")
Another way would be to manipulate the string:
print ':'.join(str(durationTime).split(':')[1:])
Related Topics
Split a Generator into Chunks Without Pre-Walking It
Get Fully Qualified Class Name of an Object in Python
How to Sort Objects by Multiple Keys
Python: Converting from Iso-8859-1/Latin1 to Utf-8
Retrieve List of Tasks in a Queue in Celery
How to Make a Selenium Script Undetectable Using Geckodriver and Firefox Through Python
How to Determine Whether a Year Is a Leap Year
Pip Cannot Uninstall <Package>: "It Is a Distutils Installed Project"
Prime Number Check Acts Strange
Python Enum, When and Where to Use
Escape String Python for MySQL
Pandas Split Column into Multiple Columns by Comma
Python Memoising/Deferred Lookup Property Decorator
Two Variables in Python Have Same Id, But Not Lists or Tuples
List Directory Tree Structure in Python
Why Does Str(Float) Return More Digits in Python 3 Than Python 2