Yacino
Yacino

Reputation: 665

How to minus time with Python

I'd like to get the time before X seconds before datetime.time.now(). For example, if the time.now() is 12:59:00, and I minus 59, I want to get 12:00:00.

How can I do that?

Upvotes: 0

Views: 3090

Answers (4)

sachin saxena
sachin saxena

Reputation: 976

You can try dateutil:

datetime.datetime.now() + dateutil.relativedelta.relativedelta(second=-60)

Upvotes: 1

Vikas Ojha
Vikas Ojha

Reputation: 6950

You need to use timedelta

from datetime import timedelta, datetime
d = datetime.now()
d = d - timedelta(minutes=59)
print d

Upvotes: 1

dfranca
dfranca

Reputation: 5322

import datetime
datetime.datetime.now() - datetime.timedelta(seconds=59)

Should do the trick

You can read more about timedelta on the documentation:

class datetime.timedelta

A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.

Upvotes: 1

heinst
heinst

Reputation: 8786

You can use time delta like this:

import datetime

print datetime.datetime.now() - datetime.timedelta(minutes=59)

Upvotes: 9

Related Questions