Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python add days in epoch time

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?

like image 880
Satish Avatar asked Dec 17 '15 02:12

Satish


People also ask

How do you add days in Python?

Use the timedelta() class from the datetime module to add days to a date, e.g. result_1 = date_1 + timedelta(days=3) .

How do I use epoch time in Python?

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.


1 Answers

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. :-)

like image 139
ShadowRanger Avatar answered Sep 21 '22 11:09

ShadowRanger