1

On the doc it says for timedelta(seconds= ), the seconds should be Between 0 and 86399 inclusive. However I hope to pass a parameter with timedelta(seconds=432000) (5 days in seconds. I understand we can pass days = 5 but it was preferred for the parma to be written in seconds. It is larger than 86399 but in console when I tested, it was still resolved to days. Is it ok to pass in seconds like this ? Many thanks for your help.

nowtime = datetime.now() print(nowtime) 2021-06-24 15:08:36.048664 plusdays = timedelta (seconds = 432000) print(nowtime+plusdays) 2021-06-29 15:08:36.048664 
1
  • 1
    If the documentation says the max is 86399, you're taking a chance if you use anything larger. It could stop working tomorrow. Commented Jun 24, 2021 at 3:16

1 Answer 1

4

The docs don't say that ;-) They say that only days, seconds, and microseconds are stored internally, and are normalized in such a way that the internal seconds stored is in range(86400).

So far as what you can pass to the constructor, just about anything is fine; e.g., even negative seconds:

>>> from datetime import timedelta >>> timedelta(hours=1, seconds=-1) datetime.timedelta(seconds=3599) 

Example

time.time() generally returns the number of seconds since 1970 began (the "Unix epoch"). That can be used directly to convert to and from a UTC datetime.

>>> import time >>> from datetime import datetime, timedelta >>> now = time.time(); datetime.utcnow() datetime.datetime(2021, 6, 24, 21, 51, 27, 939029) >>> now 1624571487.9390297 >>> datetime(1970, 1, 1) + timedelta(seconds=now) datetime.datetime(2021, 6, 24, 21, 51, 27, 939030) 

The final output is within a microsecond of when utcnow() was called.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but could you elaborate a bit? I was referring to this page and it says If the normalized value of days lies outside the indicated range, OverflowError is raised. docs.python.org/3/library/datetime.html#timedelta-objects
Which says nothing about seconds, right? It says days. All inputs are converted to a mix of (only) microseconds, seconds and days; microsecond and seconds are normalized to force them into the documented ranges, which can cause "carries" into the next higher time unit (microseconds -> seconds, and seconds -> days), and then if the final number of days is outside the documented range for days, OverflowError is raised.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.