Elias
Elias

Reputation: 3

How to remove seconds and microseconds from a timedelta?

I want to print the time delta between 2 dates without seconds or nanoseconds. I would also like to be able to extract just the day or just the month. Is this possible?

This is the code I have so far for this:

import datetime

t1 = datetime.datetime(2021, 9, 10, 10, 00)
t2 = datetime.datetime.today()

delta = t1 - t2

print(delta)

Upvotes: 0

Views: 1442

Answers (4)

ShadowRanger
ShadowRanger

Reputation: 155704

If you want to ignore second/microsecond in the original datetimes, use the replace method to set them to 0, then perform the calculation:

import datetime

t1 = datetime.datetime(2021, 9, 10, 10, 00)  # Already lacks seconds
t2 = datetime.datetime.today().replace(second=0, microsecond=0)  # Gets datetime without second/microsecond data

delta = t1 - t2

print(delta)

You can't extract the months from a timedelta (because it has no granularity beyond days; a month or year has no fixed length after all), but the .days attribute of a timedelta will tell you how many complete days it represents.

I've omitted truncating data from the timedelta itself, as the other answers have that covered adequately (and in practice, I've found most people want, or can tolerate, the truncation being performed on the inputs, not the result).

Upvotes: 0

Brian Z
Brian Z

Reputation: 373

you can use mod on the timestamp to round it to anything you want.

import datetime

t1 = datetime.datetime(2021, 9, 10, 10, 00)
t2 = datetime.datetime.today()
t2s = t2.timestamp()
# mod 60 removes seconds and fractions, mod 1 would just remove fractions of second, etc
t2s = t2s - t2s % 60
t2new = datetime.datetime.fromtimestamp(t2s)

print(t2new)

Upvotes: 0

azro
azro

Reputation: 54168

To get without seconds nor microseconds, use slice the string version

from datetime import datetime
delta = datetime(2021, 9, 10, 10, 00) - datetime.now()

print(delta)             # 15 days, 11:24:04.767145
print(str(delta)[:-10])  # 15 days, 11:24

To get the days (or month) use days property

from datetime import datetime
delta = datetime(2021, 9, 10, 10, 00) - datetime.now()

print(delta.days)       # 15
print(delta.days / 30)  # 0.5

Upvotes: 2

esqew
esqew

Reputation: 44712

You can use the days property to get the number of days in a timedelta:

import datetime

t1 = datetime.datetime(2021, 9, 10, 10, 00)
t2 = datetime.datetime.today()

delta = t1 - t2

print(delta.days)

Repl.it

Upvotes: 0

Related Questions