简体   繁体   中英

Python timedelta with seconds

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

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; eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM