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?
Use the timedelta() class from the datetime module to add days to a date, e.g. result_1 = date_1 + timedelta(days=3) .
Get Current Time in PythonUse the time. time() function to get the current time in seconds since the epoch as a floating-point number. This method returns the current timestamp in a floating-point number that represents the number of seconds since Jan 1, 1970, 00:00:00.
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. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With