How to add days in epoch time in Python
#lssec -a lastupdate -s root -f /etc/security/passwd 2>/dev/null | cut -f2 -d=
1425917335
above command giving me epoch time I want to add 90 days in that time. how do I add days in epoch time?
datetime
makes it easy between fromtimestamp
, timedelta
and timestamp
:
>>> import datetime
>>> orig = datetime.datetime.fromtimestamp(1425917335)
>>> new = orig + datetime.timedelta(days=90)
>>> print(new.timestamp())
1433693335.0
On Python 3.2 and earlier, datetime
objects don't have a .timestamp()
method, so you must change the last line to the less efficient two-stage conversion:
>>> import time
>>> print(time.mktime(new.timetuple()))
The two-stage conversion takes ~10x longer than .timestamp()
on my machine, taking ~2.5 µs, vs. ~270 ns for .timestamp()
; admittedly still trivial if you aren't doing it much, but if you need to do it a lot, consider it another argument for using modern Python. :-)