I have an error in python, when extracting one day. I'm converting to unix and extracting one day, yet the 11th of march - is always missing, no matter how big the dataset. Could anyone tell me what might be the error ?
from time import localtime, mktime, strptime, strftime
day = str(20180313)
one_day = 86400
for i in range(1,5):
print(day)
previous_day_unix = int( mktime( strptime( day, "%Y%m%d")))-one_day
day = strftime("%Y%m%d", localtime(int(previous_day_unix)))
print(day)
Daylight saving time 2018 began at 2:00 AM on March 11, 2018. Thus this day wasn't 86400
seconds.
As you can see subtracting 86400
seconds is not a good way to compute differences in days. In general, all date/time "math" operations are a little more complicated than simple multiplies and adds due to things like timezones, daylight savings, and leap years.
A better way is to use a library, such as the datetime
, which handles all of these things for you:
from datetime import datetime, timedelta
day = str(20180313)
for i in range(1, 5):
print(day)
previous_day = (datetime.strptime(day, "%Y%m%d") - timedelta(days=1))
day = previous_day.strftime("%Y%m%d")
#20180313
#20180312
#20180311
#20180310