Python adds days to the era

How to add days to an era in Python

#lssec -a lastupdate -s root -f /etc/security/passwd 2>/dev/null | cut -f2 -d= 1425917335 

the above is the team giving me an era, I want to add 90 days during this time. How to add days to the era?

+7
python unix-timestamp timedelta
source share
2 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 

In Python 3.2 and earlier, datetime objects do not have a .timestamp() method, so you should change the last line to a less efficient two-step conversion:

 >>> import time >>> print(time.mktime(new.timetuple())) 

The two-step conversion on my machine takes ~ 10 times longer than .timestamp() , taking ~ 2.5 Ξs versus ~ 270 ns for .timestamp() ; apparently still trivial if you don't do this, but if you need to do this, consider another argument for using modern Python. :-)

+10
source share

If the input is a POSIX timestamp, then to get +90 days:

 DAY = 86400 # POSIX day (exact value) future_time = epoch_time + 90*DAY 

If you want to work with datetime objects, use the UTC time zone:

 from datetime import datetime, timedelta utc_time = datetime.utcfromtimestamp(epoch_time) future_time = utc_time + timedelta(90) 

Do not use local time for date / time arithmetic (avoid naive fromtimestamp() , mktime() , naive_dt.timestamp() if you can help). To understand when this can happen, read Find if 24 hours have passed between dates - Python .

+2
source share

All Articles